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

查看:29
本文介绍了如何通过 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)的结果为null

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

例如父组件中的category 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 store设置和获取数据

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

推荐答案

Child 的 mounted 钩子在 parent 的 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天全站免登陆