Below is the parent component and child component enter code here
JavaScript
x
41
41
1
export default {
2
name : 'parentNode',
3
mounted: function () {
4
var that = this;
5
6
if (that.$store.state.auth.isAuthenticated) {
7
8
that.$store.dispatch(ActionsType.GET_ALLCOINLIST).then(function (data) {
9
// I want to use this store data in child components.
10
that.$store.state.main.data = data;
11
});
12
}
13
},
14
};
15
16
export default {
17
name : 'childNode',
18
data : function(){
19
return {
20
childData : {}
21
}
22
},
23
mounted : function(){
24
//How should I check if the data is loaded or not?
25
},
26
computed : {
27
childData : function(){
28
return this.$store.state.main.data;
29
}
30
},
31
watch : {
32
childData : function(){
33
this.makeChart();
34
}
35
},
36
methods : {
37
makeChart : function(){
38
console.log('this function make a chart.');
39
}
40
}
41
}
I want to draw a new chart whenever the $store(vuex) data changes. However, since the response of this data is asynchronous, when the child component is loaded, it may or may not have received the data(in Parent component). I always want to draw a chart with the data I received when the child component was initially loaded. The components of vue are also asynchronously loaded, so in this case, how can I control it? As of now, if the child component is initially loaded, the chart may or may not be drawn. I look forward to answering from the vue expert. Thank you.
Advertisement
Answer
You can use mapState()
and watch()
:
JavaScript
1
43
43
1
import Vue from "https://cdn.skypack.dev/vue@2.6.14";
2
import * as vuex from "https://cdn.skypack.dev/vuex@3.6.2";
3
4
Vue.use(vuex)
5
6
var store = new vuex.Store({
7
state: {
8
count: 1,
9
isLoaded: false, // mutate that when async call is finished
10
},
11
mutations: {
12
increment (state) {
13
state.count++
14
}
15
},
16
actions: {
17
init() {
18
setInterval(() => this.commit('increment'), 1000) // replace this with async call and mutate isLoaded in then()
19
}
20
}
21
});
22
23
var app = new Vue({
24
el: '#app',
25
store,
26
data() {
27
return {
28
}
29
}, computed: {
30
vuex.mapState([
31
'count'
32
]),
33
},
34
watch: {
35
count() {
36
console.log('watch count', this.count)
37
}
38
},
39
mounted() {
40
this.$store.dispatch('init')
41
}
42
})
43