观察 vuejs 中的计算属性 [英] watch computed properties in vuejs

查看:24
本文介绍了观察 vuejs 中的计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查看我的计算属性 isEllipsisActive() 以查看该值是 true 还是 false,然后我想将 shouldShowArrow 设置为该值.

I am trying to watch my computed property isEllipsisActive() to see if the value is true or false and then I would like to set shouldShowArrow to this value.

当用户根据条件 this.wrap.scrollHeight <调整浏览器大小时,该值将更改.this.h1.scrollHeight;,

目前它可以工作,但只有当我刷新浏览器时,我才需要它在值更改时更新.如何查看 isEllipsisActive() 的值是否发生变化?

Currently it works but only if I refresh the browser, I need it to update when value changes. How can I watch if the value of isEllipsisActive() changes?

export default {
  data() {
    return { 
      h1: null,
      wrap: null,
      shouldShowArrow: false,
    };
  },
    isEllipsisActive() {
      if (!this.wrap && !this.h1) {
        console.log("Not initialized", 'not initalized');
        return false;
      }
      return this.wrap.scrollHeight < this.h1.scrollHeight;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.h1 = this.$refs.h1;
      this.wrap = this.$refs.wrap;
    });
  },
  watch: {
    isEllipsisActive(newValue) {
      this.h1 !== null && console.log('changed')
    },
  },
};

推荐答案

你可以试试这个方法,看看是否为你触发了手表

you can try this way and see if trigger the watch for you

watch: {
  isEllipsisActive: {
     deep: true
     handler(now){
        this.h1 !== null && console.log('changed')
     }
}

由于您的计算值与您试图观察执行的更改位于同一组件中,因此您不需要这样做.或者您可以观察其中一个值并在观察者中执行您需要的所有逻辑.但正如@Dan 在另一条评论中所说,有时我们需要观察这些计算值.当我想在 Vuex 触发器的计算 getter 更改后执行额外代码时,我使用此逻辑.

since your computed value is in the same component that you are trying to watch the change performed you should not need to do that. Or you can watch one of the values and perform all the logic you need inside the watcher. But As @Dan say in another comment, sometimes we need to watch those computed values. I use this logic when I want to execute extra code after the computed getter from Vuex trigger changes.

这篇关于观察 vuejs 中的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆