vue.js - 从 vue watcher 访问组件实例

标签 vue.js vuejs2 watch computed-properties

我正在做一个类似于账单经理的项目,所以我希望每次数量或单位值发生变化时都重新计算小计,我尝试并搜索了使用观察器或计算属性来完成此操作,但我找不到正确的方法,因为我需要在另一个更改时访问元素的整个范围,就像这样。

模型结构:

  • 细节
  • 数量
  • 单位值(value)
  • 小计(应该是计算的或更新的)

所以我认为我应该能够做这样的事情:

    Vue.component('item', {
    template: '#item',
    props: {
      item: Object,
    },
    computed:{
        total: function(){ 
            return this.quantity*this.unit_value;
         }
    },
    watch:{
      'item.quantity':()=>{
        this.subtotal = this.quantity*this.unit_value;
      }
    }
  });

我有几个组件正在从列表中读取

我在同一代码中合并了使用 watcher 和 computed 的方法以使其更短。

问题是我还没有找到从内部访问 hole 元素的方法,谁能解释一下正确的方法?谢谢

最佳答案

你不应该在那里使用箭头函数,使用方法声明。

如果你想观察 item 对象的属性,你必须观察 item 对象本身,另外使用 deep : true 观察者的标志。

最后的细节,您正在使用多个未在您的data 中声明的属性。声明它们,否则它们将不会是响应式(Reactive)的,即当它们发生变化时,computed 不会重新计算。

查看代码:

Vue.component('item', {
  template: '#item',
  props: {
    item: Object,
  },
  data() {
    return {
      subtotal: null,         // added data properties
      quantity: null,
      unit_value: null
    }
  },
  computed: {
    total: function() {
      return this.quantity * this.unit_value;
    }
  },
  watch: {
    item: {                          // watching for item now
      deep: true,                    // using deep: true
      handler() {                    // and NOT using arrow functions
        this.subtotal = this.quantity * this.unit_value;
      }
    }
  }
});

关于vue.js - 从 vue watcher 访问组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49563044/

相关文章:

javascript - Vue.js 没有自动更新

javascript - Vue.js:如何在 .vue 模板文件内的 vue 方法中设置数据变量

javascript - 如何将数据(json)传递给 vue 实例

用于在 C 中监视文件系统的跨平台 API?

javascript - Angular 范围。$watchCollection 不多次检查集合

typescript - NestJS- Mongoose : cannot access fullDocument on ChangeEvent<any>

javascript - vue2.js 组件 vmodel 传递数据

javascript - 从axios访问VUE JS的数据

vue.js - 如何在 vue js 上的循环(超过 1 个循环)完成后调用方法?

javascript - 如何在 .js 文件中使用 Vue i18n 翻译?