How to pass the result of a computed property to another component in Vue

21 Views Asked by At

I have been struggling since a few days to pass the result of a computed property to another component. The computed property is defined in HomeView.vue, and I would like to insert the result of the computed property in the file AboutView.vue. How can I do it ?

I guess I have to create another component with only the definition of the data and the computed property, and insert it in AboutView.vue, but it will complicate everything since there are methods in HomeView.vue that uses the datas "quantities" and "prices". So it will be hard to access to them if I move them to a new component;

Thank you for any help !

<!--AboutView.vue-->

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <p> Total price is : </p>
    <!-- INSERT TOTAL PRICE HERE -->
  </div>
</template>

<script>


export default {
    name: 'AboutView',
    components: {
        
    }
}
</script>
<!--HomeView.vue-->

<template>
    <router-link to="/about">
        <button class="total">
            <TotalPriceChild :propTotalPrice="totalPrice" />
        </button> 
    </router-link> 
</template>

<script>
import TotalPriceChild from '@/components/TotalPriceChild.vue'

export default {
    name: 'HomeView',
    components: {
        TotalPriceChild,
    },
    data() {
        return{
            quantities: {
                item1: 0,
                item2: 0,
            },
            prices: {
                item1: 10,
                item2: 10,
            }
        }
    },
    computed: {
        totalPrice(){
            return (this.quantities.item1 * this.prices.item1)
            + (this.quantities.item2 * this.prices.item2)
        }
    }
}
<!--TotalPriceChild.vue-->

<template>
    <div>
        <p>{{ propTotalPrice }}</p>T
    </div>
</template>
  
<script>
    export default {
        name: 'TotalPriceChild',
        props: {
            propTotalPrice: {
                type: Number,
                required: true
            }
        }
    };
</script>
0

There are 0 best solutions below