Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

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

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

main 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?

Note that I do not want to redo the calculations done in lineTotal but instead use the computed properties directly.

like image 726
howellmartinez Avatar asked Jul 26 '16 02:07

howellmartinez


People also ask

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

How do computed properties work in Vue?

In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.

How do you access a root component from a child instance in Vue?

We can access the root instance of from a child component with the $root property. The code above created a rootFoo computed property from the root Vue instance's foo component and displayed it inside the foo component. So we get foo displayed.


1 Answers

You have to name the children, for example by means of the v-ref directive. Then from the parent you resolve the children properties with this.$refs.mychild.myproperty

like image 100
gurghet Avatar answered Oct 13 '22 18:10

gurghet