【问题标题】:How can I send data from parent to child component by vuex store in vue component?如何通过 vue 组件中的 vuex 存储将数据从父组件发送到子组件?
【发布时间】:2018-09-04 08:25:15
【问题描述】:

我的父组件是这样的:

<template>
    ...
        <search-result/>
    ...
</template>
<script>
    import {mapActions} from 'vuex'
    ...
    export default {
        ...
        props: ['category'],
        mounted() {
            this.updateCategory(this.category)
        },
        methods: {
            ...mapActions(['updateCategory']),
        }
    }
</script>

我的子组件是这样的:

<template>
    ...
</template>
<script>
    import {mapGetters} from 'vuex'
    ...
    export default {
        ...
        mounted() {
            console.log(this.getCategory)
        },
        computed: {
            ...mapGetters(['getCategory'])
        },
    }
</script>

我的模块 vuex 在组件之间发送数据,如下所示:

import { set } from 'vue'
...
// initial state
const state = {
    category: null
}
// getters
const getters = {
    getCategory: state =>  state.category
}
// actions
const actions = {
    updateCategory ({commit}, payload) {
        commit(types.UPDATE_CATEGORY, payload)
    }
}
// mutations
const mutations = {
    [types.UPDATE_CATEGORY] (state, payload) { 
        state.category = payload
    }
}
export default {
    state,
    getters,
    actions,
    mutations
}

我尝试过这样,但它不起作用

如果代码执行,子组件中console.log(this.getCategory)的结果为null

例如父组件中的category prop = 7。子组件中console.log(this.getCategory)的结果是否应该= 7

为什么它不起作用?为什么结果为空?

注意

我可以通过 prop 发送类别数据。但在这里我不想使用道具。我想通过 vuex 存储发送数据。所以我只想通过 vuex store 设置和获取数据

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex vuex-modules


    【解决方案1】:

    子级的mounted 挂钩在父级的mounted 挂钩之前执行。 (为什么?见this link

    console.log(this.getCategory) 发生在 this.updateCategory(this.category) 之前。

    因此,您会在控制台中获得null

    如果您将console.log(this.getCategory) 放入updated 钩子中,稍后您将在控制台中获得正确的值。

    【讨论】:

    • 我尝试在父组件中将mounted更改为created,它可以工作
    【解决方案2】:

    Jacob goh 指出了问题所在。

    为了解决这个问题,你可以在子组件的mounted钩子中使用vm.$nextTick()来确保整个视图已经被渲染并且父组件的mounted钩子被调用。

    <template>
        ...
    </template>
    <script>
        import {mapGetters} from 'vuex'
        ...
        export default {
            ...
            mounted() {
                this.$nextTick(() => {
                    console.log(this.getCategory);
                })
            },
            computed: {
                ...mapGetters(['getCategory'])
            },
        }
    </script>
    

    这里是working fiddle

    您可以在此处详细了解为什么使用vm.nextTick()Vue updates the DOM asynchronously

    【讨论】:

    • 我尝试在父组件中将mounted更改为created,它可以工作
    猜你喜欢
    • 2020-09-05
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2016-03-18
    • 2021-01-20
    • 2021-02-15
    • 2020-09-28
    相关资源
    最近更新 更多