Reputation: 873
I try to use data from vuex during mounted lifecycle hook. However, it seems like mounted life cycle hook is excuted before I get the data from vuex. How do I access the data from vuex and use it during mounted life cycle hook?
The code is as below.
I bring data by getters like this.
computed:{
targetCounty(){
return this.$store.getters['parkingModule/byCounty'][this.countyname]
}
Then I need to feed this data to my class constructur by init() method
init(){
scene =new THREE.Scene();
const canvas=document.querySelector('#myCanvas');
canvas.width=innerWidth;
canvas.height=innerHeight;
camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1,
1000 );
renderer=new THREE.WebGLRenderer({canvas:canvas})
renderer.setSize( window.innerWidth, window.innerHeight );
let texture = new THREE.TextureLoader().load('disc.png');
let rawRad = this.rawRadius
console.log(this.targetCounty)
const meshobject =new
ParkingSpot(rawRad,this.targetCounty.length,100,texture,this.targetCounty)
sphereMesh= meshobject.createMesh();
camera.position.z = 5
scene.add(sphereMesh);
console.log(sphereMesh.material.size)
},
this init() method is invoked during mounted life cycle hook like this.
mounted(){
this.init()
this.animate();
// window.addEventListener()
},
created(){
console.log(this.targetCounty)
// setTimeout(()=>{console.log(this.targetCounty[0])},3000)
},
However, when I log this.targetCounty, it returns empty array. So I got around it by rendering computed property in DOM cause computed property runs only the element is rendered.
<template>
<div>
<canvas id="myCanvas"></canvas>
</div>
<p v-show='false'>{{targetCounty}}</p>
</template>
I created dummy DOM element only to get the computed property for my mounted life cycle(I think it's very bad approach)
What would be the solution for solving this problem?
Upvotes: 0
Views: 752
Reputation: 138276
You could use vm.$watch()
in the mounted()
hook to observe the store's getter for the initial value:
export default {
mounted() {
const unwatch = this.$watch(
() => this.$store.getters['parkingModule/byCounty'][this.countyname],
targetCounty => {
if (targetCounty) {
// handle initial value here...
this.targetCounty = targetCounty
this.init()
this.animate()
unwatch()
}
}
)
}
}
Upvotes: 2
Reputation: 65
Why don't you try making a function that explicitly returns the value and then invoke it in the mounted() lifecycle hook, saving it into a constant. Then pass that constant into your init function.
const targetCountry = this.$store.getters['parkingModule/byCounty'[this.countyname]
this.init(targetCountry)
Upvotes: 0