如何通过 vuex store 在 vue 组件中将数据从父组件发送到子组件?

How can I send data from parent to child component by vuex store in vue component?

我的父组件是这样的:

<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

设置和获取数据

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

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>

这里是working fiddle

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