如何通过vue组件中的vuex存储将数据从父组件发送到子组件? [英] How can I send data from parent to child component by vuex store in vue component?

查看:473
本文介绍了如何通过vue组件中的vuex存储将数据从父组件发送到子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的父组件是这样的:

<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在这样的组件之间发送数据:

My modules vuex to send data between components like this :

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
}

我尝试那样,但是不起作用

I try like that, but it does not works

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

If the code executed, the result of console.log(this.getCategory) in the child component is null

例如,父组件中的类别prop =7.子组件中console.log(this.getCategory)的结果应为7

For example category prop in the parent component = 7. Should the result of console.log(this.getCategory) in the child component = 7

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

Why it does not work? Why the result is null?

注意:

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

I can just send the category data via prop. But here I do not want to use prop. I want to send data via vuex store. So I want to set and get data only via vuex store

推荐答案

在父母的mounted钩子之前执行孩子的mounted钩子. (为什么?请参见

Child's mounted hook is executed before parent's mounted hook. ( why? See this link)

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

因此,您会在控制台中找到null.

Therefore, you get null in the console.

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

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

这篇关于如何通过vue组件中的vuex存储将数据从父组件发送到子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆