Vue里面的计算属性(computed)以及computed 和methods的不同

199 阅读1分钟

computed和methods不同总结如下:

**我们可以得出规律: **

**computed: 当计算属性依赖的内容发生改变时, 才会重新计算 ** methods: 当页面需要重新渲染, 就会重新计算 ** computed 有缓存机制, 页面渲染更高效, 如果 computed 和 methods 都能实现效果, 推荐使用 computed **

具体代码分析如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    **把vue先引过来**
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    // 定义一个应用,里面放vue各种属性方法,里面的属性方法都要写成对象的形式
    // 比如methods:{}  computed:{}  如果里面是对象,都要return出去,比如data(){return}
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          price: 20,
          num: 100,
          hello: "hello world",
        };
      },

      // 计算属性
      computed: {
        // 所有的计算属性都放在计算属性这个对象里面,并return出去
        total() {
          // vue里面 this就是实例化的data里面的内容
          return this.num * this.price + "====> " + Date.now();
        },
      },
      //   用methods方法也可以实现计算属性做的事,因为逻辑都是写在mentods里面的
      methods: {
        // 把要做的计算总价逻辑写在methods里面 并return出去
        // 加上时间戳是为了理解computed和methods的不同
        sumPrice() {
          return this.price * this.num + "====> " + Date.now();
        },
      },
      // 模板,里面要用的是总价函数返回的结果,而不是总价这个函数,所以加()
      template: `
      <h2>{{hello}}</h2>
        <h1> {{sumPrice()}}</h1>
        `,
    });
    const vm = app.mount("#root");
  </script>


<!-- computed和methods不同总结如下: -->
<!-- 我们可以得出规律: -->

<!-- computed: 当计算属性依赖的内容发生改变时, 才会重新计算 -->

<!-- methods: 当页面需要重新渲染, 就会重新计算 -->

<!-- computed 有缓存机制, 页面渲染更高效, 如果 computed 和 methods 都能实现效果, 推荐使用 computed -->
</html>