Vue js在组件之间发送数据

时间:2017-09-07 16:07:42

标签: javascript vue.js vuejs2 vue-component

我想知道如何在两个组件之间发送数据。所以我想向另一个组件发送在selectedBase.price上呈现的动态值,并在另一个组件上呈现。我尝试过道具但没有成功。

<v-layout row wrap primary-title v-for="base in bases" :key="base.id">
        <v-layout column>
            <v-flex xs6 offset-xs3>
                <v-avatar size="80px" class="grey lighten-1">
                    <img :src="base.href" :class="{selected: selectedBase.id == base.id}" @click="selectedBase = base" alt="avatar">
                </v-avatar>
            </v-flex>
        </v-layout>
        <v-layout column>
            <v-flex xs6 offset-xs4>
                <v-subheader>{{base.name}} {{base.price}}€ {{selectedBase.price}}</v-subheader>
            </v-flex>
        </v-layout>
    </v-layout>

<script>

export default {

    data() {
            return {
                selectedBase: {},
                bases: [{
                    id: 1,
                    name: "black",
                    price: 4,
                    href: "../../static/black.jpg"
                }, {
                    id: 2,
                    name: "white",
                    price: 6,
                    href: "../../static/white.jpg"
                }]
            }
        },
        computed: {

            totalBase: function() {
                var totalBase = 0;
                for (var i = 0; i < this.bases.length; i++) {
                    if (this.bases[i].selected) {
                        totalBase += this.bases[i].price;
                    }
                }
                return totalBase;
            }
        },
        methods: {
            getSelectedBase() {
                return this.selectedBase;
            }
        }
}

</script>

1 个答案:

答案 0 :(得分:1)

是的,props是正确的方式。

<强> ParentComponent.vue

<template>
    <your-component your-prop="123"></your-component>
</template>

<script>
    import YourComponent from '/path/to/YourComponent'

    export default {
        data() {
            return { }
        },
        components { YourComponent }
    }
</script>

<强> ChildComponent.vue

<template>
    <div>My prop is: {{ yourProp }}</div>
</template>

<script>
    export default {
        data() {
            return { }
        },
        props: ['your-prop']
    }
</script>

你也可以使用Vuex在你的应用程序之间共享状态,但我认为情况并非如此。

相关问题