📜  Vue.js 计算属性

📅  最后修改于: 2022-05-13 01:56:49.250000             🧑  作者: Mango

Vue.js 计算属性

Vue 是一个用于构建用户界面的渐进式框架。核心库仅专注于视图层,易于获取并与其他库集成。 Vue 还可以完美地结合现代工具和支持库来支持复杂的单页应用程序。

在 Vue.js 中,可以使用括号输出任何数据值。但是,这可以承载小型计算,因为它仅限于单个 JavaScript 表达式,而且模板应该只关注向用户显示数据而不执行任何逻辑计算。为了避免单个表达式的这种限制并拥有更多的声明性模板,我们使用 Vue.js 的计算属性。计算值遵循相同的旧插值,但计算逻辑在 JavaScript 中定义。

示例 1:

index.html


    


    
          

{{ fullName }}

       
    


app.js
const parent = new Vue({
  el: '#parent',
  data: {
    fName: 'Aiser',
    lName: 'Wold'
  },
  
  computed: {
    fullName: function () {
      return `Full Name :
        ${this.fName} ${this.lName}`
    }
  }
})


index.html


    


    
        

Animal Helping NGO

          

Total Members :            {{ totalMembers }}           

             

Donations from Male members :            {{ maleDonation }}           

             

Donations from female members :            {{ femaleDonation }}           

       
    


app.js
const parent = new Vue({
    el: '#parent',
    data: {
        mMembers: ['Arun', 'Raj', 'Kabir',
                   'Santanu','Aiser','Mikie'],
        fMembers: ['Tina','Jagriti','Nupur',
                   'Nancy','Rinkle']
    },
  
    computed: {
        totalMembers: function() {
            return this.mMembers.length + 
                   this.mMembers.length
        },
        maleDonation: function() {
            return this.mMembers.length * 100;
        },
        femaleDonation: function() {
            return this.fMembers.length * 50
        }
    }
})


应用程序.js

const parent = new Vue({
  el: '#parent',
  data: {
    fName: 'Aiser',
    lName: 'Wold'
  },
  
  computed: {
    fullName: function () {
      return `Full Name :
        ${this.fName} ${this.lName}`
    }
  }
})

输出:

计算属性

示例 2:

索引.html



    


    
        

Animal Helping NGO

          

Total Members :            {{ totalMembers }}           

             

Donations from Male members :            {{ maleDonation }}           

             

Donations from female members :            {{ femaleDonation }}           

       
    

应用程序.js

const parent = new Vue({
    el: '#parent',
    data: {
        mMembers: ['Arun', 'Raj', 'Kabir',
                   'Santanu','Aiser','Mikie'],
        fMembers: ['Tina','Jagriti','Nupur',
                   'Nancy','Rinkle']
    },
  
    computed: {
        totalMembers: function() {
            return this.mMembers.length + 
                   this.mMembers.length
        },
        maleDonation: function() {
            return this.mMembers.length * 100;
        },
        femaleDonation: function() {
            return this.fMembers.length * 50
        }
    }
})

输出:

计算属性

参考: https://012.vuejs.org/guide/computed.html