【问题标题】:Vue js sending data between componentsVue js在组件之间发送数据
【发布时间】:2017-09-07 16:07:42
【问题描述】:

我想知道如何在两个组件之间发送数据。所以我想将在 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>

【问题讨论】:

  • 您实际上只能使用道具在组件之间共享数据。但推荐的方式是使用 Vuex 来共享数据。
  • 好的,谢谢。你能解释为什么在这种情况下使用 Vuex 而不是 props 更好吗?我从来没有使用过 Vuex,我不知道它是如何工作的。谢谢
  • 我可以为您编写带有 props 的“vanilla”Vue 示例,其次是 Vuex,但后来,我现在很忙。你能等1个小时吗?
  • 从问题中不清楚涉及哪些组件。你能澄清一下吗?
  • @WaldemarIce 是的,当然。谢谢

标签: javascript vue.js vuejs2 vue-component


【解决方案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 在您的应用程序之间共享状态,但我认为不是这样。

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2018-02-12
    • 2019-10-23
    • 2018-05-15
    • 2020-09-20
    • 2020-09-24
    • 2017-03-09
    • 2020-08-17
    • 2022-01-15
    相关资源
    最近更新 更多