简体   繁体   English

从父级访问Vue中组件的计算属性

[英]Accessing the computed properties of components in Vue from the parent

How do you access the computed properties of components in Vue from the parent? 如何从父级访问Vue中组件的计算属性?

In this example, I have a cart with item components and I want to compute and display the sum of the cart items: 在这个例子中,我有一个带有项目组件的购物车,我想计算并显示购物车项目的总和:

cart.js cart.js

var vm = new Vue({

  el: '#cart',

  components: {
    cartItem: require('./components/cart-item.js'),
  },

  data: {
    items: [
      { name: 'apple', qty: 5, price: 5.00 },
      { name: 'orange', qty: 7, price; 6.00 },
    ],
  },

  computed: {
    // I want to do something like this and access lineTotal from cart
    cartTotal: function() {
      return this.items.reduce(function(prev,curr) {
        return prev + curr.lineTotal;
      }, 0)
    }
  }
});

cart-item.js 购物车,item.js

module.exports = {
    template: require('./cart-item.template.html'),
    props: ['fruit'],
    computed: {
      lineTotal: function() {
        return this.fruit.price * this.fruit.qty;
      }
    },
};

main html 主要的HTML

<li v-for="item in items" is="cart-item" :fruit="item">

...

@{{ cartTotal }}

How do I access the lineTotal properties of each cart-item to use in summing cartTotal ? 如何访问每个购物车项目的lineTotal属性以用于cartTotal

Note that I do not want to redo the calculations done in lineTotal but instead use the computed properties directly. 请注意,我不想重做lineTotal完成的计算,而是直接使用计算属性。

You have to name the children, for example by means of the v-ref directive. 您必须为子项命名,例如通过v-ref指令。 Then from the parent you resolve the children properties with this.$refs.mychild.myproperty 然后从父级解析子属性this.$refs.mychild.myproperty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM