How can I send data from parent component to child component by vuex store in vue component?
My parent component:
<template>
...
<search-result/>
...
</template>
<script>
import {mapActions} from 'vuex'
...
export default {
...
props: ['category'],
mounted() {
this.updateCategory(this.category)
},
methods: {
...mapActions(['updateCategory']),
}
}
</script>
My child component:
<template>
...
</template>
<script>
import {mapGetters} from 'vuex'
...
export default {
...
mounted() {
console.log(this.getCategory)
},
computed: {
...mapGetters(['getCategory'])
},
}
</script>
My vuex modules 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 so hard but it doesn't work
If the code is executed the result of console.log (this.getCategory) in the child component is null
For example prop category in parent component = 7. If console.log (this.getCategory) result in child component = 7
Why doesn't it work? Why is the result null?
Note :
I can just send category data via prop. But I don't want to use a prop here. I want to send data via vuex store. So I want to install and get data only via vuex store
source to share
The child mounted
is executed before the parent 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)
.
Hence, you get null
in the console.
If you put console.log(this.getCategory)
in a updated
hook, you will get the correct value in the console later.
source to share
Jacob goh pointed out the problem.
To solve this problem, you can use vm.$nextTick()
in child component mounted
to make sure that the whole view has and is called by the parent mounted
hook.
<template>
...
</template>
<script>
import {mapGetters} from 'vuex'
...
export default {
...
mounted() {
this.$nextTick(() => {
console.log(this.getCategory);
})
},
computed: {
...mapGetters(['getCategory'])
},
}
</script>
Here is a working violin
You can read more about why to use it vm.nextTick()
here: Vue updates the DOM asynchronously
source to share