Vue中computed与methods的区别详解

Vue中computed可以用来简单的拼接需要展示的数据

Vue中computed与methods的区别详解

computed and methods

拼接展示数据的任务, 也可以用methods完成, 但当页面的数据变化时, methods中的方法会被重新调用(产生不必要的性能消耗), 而methods内的方法只有和自身有关的数据变化时才会被调用

一个简单的实例

Vue中computed与methods的区别详解

computed只在初始化时被调用

computed只在初始化时被调用

methods会在数据变化时被调用, 即使变动的数据与自身无关

测试源码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>computed的使用</title>
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
  <div id="root">
  </div>
  <script>
    var vm = new Vue({
      el: "#root",
      data: {
        name: "zhaozhao",
        age: 13,
        hobby: 'Python',
        nameAgeStyle: {
          fontSize: "20px",
          color: "#0c8ac5"
        }
      },
      template: `<div>
        <div v-bind:style="nameAgeStyle">computed方式渲染: {{nameAndAge}}</div>
        <div v-bind:style="nameAgeStyle">methods 方式渲染: {{getNameAndAge()}}</div>
        <br>
        <input type="text" v-model="hobby">
        <div>爱好: {{hobby}}</div>
        <div>{{noUse()}}</div>
        </div>`,
      computed: {
        nameAndAge: {
          get(){
          console.log('调用computed');
          return `${this.name} ==> ${this.age}`;
          }
        }
      },
      methods: {
        getNameAndAge() {
          console.log('调用methods');
          return `${this.name} ==> ${this.age}`;
        },
        noUse(){
          console.log("=methods==nouse==");
        }
      }
    })
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。