vue中 methods watch computed的执行顺序

vue中 methods watch computed的执行顺序

今天在做项目的时候,遇到一个问题,一直告诉我一个函数未定义。因为我是使用的计算属性(computed)给子组件传递的数据,于是我就写了一个demo测试了一下。

	<div id="app">
      <h2>{{currentTabComponent}}</h2>
      <button @click="changTab">点击切换</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      const app = new Vue({
        el: "#app",
        data: {
          currentTab: "张三",
          tabs: ["张三", "李四"],
        },
        computed: {
          currentTabComponent() {
            console.log("computed");
            return this.currentTab;
          },
        },
        watch: {
          currentTab() {
            console.log("watch");
          },
        },
        methods: {
          changTab() {
            console.log("methods");
            for (let item of this.tabs) {
              if (this.currentTab != item) {
                this.currentTab = item;
                break;
              }
            }
          },
        },
      });
    </script>

然后一打开浏览器的时候,就看到computed执行了一次
在这里插入图片描述
然后这时,我点击了切换按钮,这里我们可以看到是按顺序执行了method,watch,computed
在这里插入图片描述
综上所述:
computed:在文档首次加载时会执行一次,当Vue实例中的data属性变化并被computed中的计算属性引用时,所有的相关计算属性又会执行一次。

watch:侦听器,当computed执行完毕后,执行watch继续侦听缓存中的对应Vue实例的data属性,如若再次侦听到data属性值有变,便又会触发computed。

methods:存放方法的对象,靠某种行为触发里面对应的方法


版权声明:本文为Kavii_a原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。