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?
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()
}
}
)
}
}