Vue's computed properties (getter, setter), caching of computed properties

Vue calculated attributes: For any complex logic, choose to use calculated attributes

<body>
  <div id="app">
  <!--计算属性引用时不用加(),把其当作一个属性-->
    <h2>{
   
   {totalPrice}}</h2>
  </div>
  <script src="../js/vue.js"></script>
  <script>
    var vm=new Vue({
     
     
      el:'#app',
      data:{
     
     
        books:[
          {
     
     id:110,name:"unix",price:119},
          {
     
     id:111,name:"unix",price:105},
          {
     
     id:112,name:"unix",price:98},
          {
     
     id:113,name:"unix",price:87},
        ]
      },
      computed:{
     
     
        totalPrice:function(){
     
     
          //计算books的总价
         let result = 0;
         for(let i = 0;i<this.books.length;i++){
     
     
           result +=this.books[i].price
         }
         return result;
        }
      }
    })
  </script>
</body>

A more concise way of dealing with the sum:

         let result =0;
          for (let i in this.books){
    
    
            result+=this.books[i].price;
          }
          return result;
          let result =0;
          //book直接为数组中的每一项
          for (let book of this.books){
    
    
            result+=book.price;
          }
          return result;

reduce(): Calculate the sum of the added array elements.

 totalPrice:function(){
    
    
          return this.books.reduce((sum,cur)=>{
    
    
            return sum + cur.price
          },0)
        }
 //在该方法中,cur依次为books中的每一项,而sum初始为0,开始与cur累加

Calculate attributes to realize string splicing:

  <div id="app">
    <h2>{
   
   {fullName}}</h2>
  </div>
  
  <script src="../js/vue.js"></script>
  <script>
    var vm=new Vue({
     
     
      el:'#app',
      data:{
     
     message:'你好',firstName:'Lebron',lastName:'James'},
      computed:{
     
     
        fullName:function(){
     
     
          return this.firstName + ' '+ this.lastName
        }
      }
    })
  </script>

Setter and getter of calculated property

Calculated using the attribute properties manner, i.e. a reference { {fullname}}instead of { {fullname()}}, the above reasons :( modify the code string concatenation)

fullName属性对应的是一个对象,相当于在computed对象中定义一个属性fullName,对应的依旧是一个对象,
所以使用fullName属性,就写成{
   
   {fullName}}.
计算属性中会有一个set方法、一个get方法,完整的计算属性应该写成下面的样子:
       // 需要获取fullName的值的时候,就会调用get方法,
       //所以页面显示的时abc,修改return的值就会更改fullName的值。
      computed: {
    
    
        // 计算属性的底层:
        fullName: {
    
    
          set: function () {
    
    
          },
          // 需要获取fullName的值的时候,就会调用get方法,
          //所以页面显示的时abc,修改return的值就会更改fullName的值。
          get: function () {
    
    
           return 'abc'
           //return this.firstName + ' '+ this.lastName
          }
        }
      }

Generally, set is not used, because the purpose of calculating attributes is to calculate a value and then return the result. Set is to set the value of the calculated attribute. It is also possible to delete only write get and become a read-only attribute:

      computed: {
    
    
        fullName: {
    
    
          get: function () {
    
    
            return 'abc'
          }
        }
      }

When there is no set method, the code can be abbreviated and written directly as: (the original writing method used)

      computed: {
    
    
        fullName: function () {
    
    
            return 'abc'
          }
      }

You can also add the set method:

      computed: {
    
    
        fullName: {
    
    
          set: function () {
    
    
            console.log('--调用了set方法');
          }, 
          get: function () {
    
    
            return 'abc'
          }
        } 

Modify the value of fullName in the debugging tool to see that the set method is called:
Insert picture description here
use the set method of fullName:

        fullName: {
    
    
          set: function (newValue) {
    
    //传入一个参数
            console.log('--调用了set方法',newValue);
            const name = newValue.split(' ');
            this.firstName =  name[0];
            this.lastName = name[1];
            console.log(this.firstName);
            console.log(this.lastName);
          },
          get: function () {
    
    
            return this.firstName + ' '+ this.lastName;
          }
          }

Operate on the console, modify the fullName displayed on the page by modifying the value of vm.fullName and processing in the set method to modify the values ​​of this.firstName and this.lastName.
Insert picture description here

Comparison of calculated attributes and methods (cache of calculated attributes):

The calculated attribute will be cached, and the calculated attribute will only be called once when it is used multiple times, and the method in methods will be called several times when it is used several times.

<body>
  <div id="app">
    <!-- 1 -->
    <h2>{
   
   {firstName}}{
   
   {lastName}}</h2>
    <!-- 使用methods -->
    <h2>{
   
   {getFullName()}}</h2>
    <h2>{
   
   {getFullName()}}</h2>
    <h2>{
   
   {getFullName()}}</h2>
    <!-- 使用computed -->
    <h2>{
   
   {fullName}}</h2>
    <h2>{
   
   {fullName}}</h2>
    <h2>{
   
   {fullName}}</h2>
  </div>
  
  <script src="../js/vue.js"></script>
  <script>
    var vm=new Vue({
     
     
      el:'#app',
      data:{
     
     message:'你好',firstName:'Lebron',lastName:'James'},
      methods:{
     
     
        getFullName:function(){
     
     
          console.log('调用了methods');
          return this.firstName + ' '+ this.lastName
        }
      },
      computed:{
     
     
        fullName:function(){
     
     
          console.log('调用了computed');
          return this.firstName + ' '+ this.lastName
        }
      }
    })
  </script>
</body>

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43812504/article/details/114595927