vuejs能否监听计算属性?

为什么方法一的这种写法能监听到popupMsg的变化,但是方法二不能监听的popupMsg的变化?

方法一
export default {
  data() {
    return {
      popupMsg: ''
    }
  },
  methods: {
    getData() {
      this.$store.dispatch('userGroup/getManualTags', param).then(res => {
        this.popupMsg = this.$store.state.userGroup.manualTags.popupMsg;
      })
    }
  },
  mounted() {
    this.getData();
  },
  watch: {
    popupMsg(curVal, oldVal) {
      console.log(curVal);
      console.log(oldVal);
      this.$message.error(curVal);
    }
  }
}

方法二
export default {
  data() {
    return {
    }
  },
  computed: {
    popupMsg() {
      return this.$store.state.userGroup.manualTags.popupMsg;
    }
  },
  methods: {
    getData() {
      this.$store.dispatch('userGroup/getManualTags', param);
    }
  },
  mounted() {
    this.getData();
  },
  watch: {
    popupMsg(curVal, oldVal) {
      console.log(curVal);
      console.log(oldVal);
      this.$message.error(curVal);
    }
  }
}
阅读 17.2k
5 个回答

并不是第二种方法有问题,而是第二种写法如果你只对popupMsg赋值了一次,watch是不会对第一次赋值做出任何反应的;this.$store.state.userGroup.manualTags.popupMsg的初始值是什么?

调用getData之后.store里面的popupMsg改变了吗.

第二种写法看着太奇怪了,同一个数据又是computed又是watch的。
computed是通过其他变量计算来改变一个属性,而观察watch是观察一个特定的值,当该值变化时执行特定的函数。
一般标准就是data里定义好数据容器,methods或者created,mounted里边调接口,watch监控数据变化。

计算属性是当data里的属性变化后重新计算返回结果。你在data里定义个变量,把vuex的值赋值给他,用computed就会监听到变化了。

computed 可以写 gettersetter 的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题