从vue观察器访问组件实例

时间:2018-03-29 18:43:38

标签: vue.js vuejs2 watch computed-properties

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

模型结构:

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

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

    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;
      }
    }
  });

我从列表中读取了几个组件

我使用观察者合并了该方法,并使用相同的代码进行计算,以缩短它。

问题在于我还没有找到从内部进入洞元素的方法,任何人都可以解释正确的方法吗?感谢

1 个答案:

答案 0 :(得分:2)

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

如果您想要查看item对象的属性,则必须注意item对象本身,并另外使用观察者的deep: true标志。

最后一个细节,您正在使用未在data中声明的多个属性。声明它们,否则它们不会被动反应,也就是说,计算机在变化时不会重新计算。

参见代码:

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;
      }
    }
  }
});