如何通过VUE组件中的Vuex Store将数据从父母发送到子组件



我的父组件很喜欢:

<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
}

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

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

例如,parent component = 7中的类别prop。应在子console.log(this.getCategory(的结果= 7

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

注意

我可以通过道具发送类别数据。但是在这里,我不想使用道具。我想通过VUEX商店发送数据。因此,我想仅通过Vuex Store设置并获取数据

儿童的mounted钩在父式mounted挂钩之前执行。(为什么?查看此链接(

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

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

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

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>

这是工作小提琴

您可以在此处了解有关为什么使用vm.nextTick()的更多信息:VUE更新DOM异步

最新更新