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:存放方法的对象,靠某种行为触发里面对应的方法

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值