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

空扰寡人 提交于 2019-11-29 18:05:18

Child's mounted hook is executed before parent's mounted hook. (why? See https://forum.vuejs.org/t/order-of-lifecycle-hooks-for-parent-and-child/6681/2?u=jacobgoh101)

console.log(this.getCategory) happens before this.updateCategory(this.category).

Therefore, you get null in the console.

If you put console.log(this.getCategory) in updated hook, you would be getting the right value in the console later on.

Jacob goh has pointed out the problem.

To solve this issue you can make use of vm.$nextTick() in the child component's mounted hook to ensure that the entire view has been rendered and the parent's mounted hook is called.

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

Here is the working fiddle

You can learn more about why use vm.nextTick() here: Vue updates the DOM asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!