问题描述
我尝试在挂载生命周期钩子期间使用来自 vuex 的数据。 但是,在我从 vuex 获取数据之前,似乎已执行了已安装的生命周期钩子。 如何从 vuex 访问数据并在挂载生命周期钩子期间使用它?
代码如下。
-
我通过这样的 getter 带来数据。
computed:{ targetCounty(){ return this.$store.getters['parkingModule/byCounty'][this.countyname] }
-
然后我需要通过 init() 方法将此数据提供给我的类构造器
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) },
-
这个 init() 方法是在像这样挂载的生命周期钩子期间调用的。
mounted(){ this.init() this.animate(); // window.addEventListener() },created(){ console.log(this.targetCounty) // setTimeout(()=>{console.log(this.targetCounty[0])},3000) },
但是,当我记录 this.targetCounty 时,它返回空数组。所以我解决了它 通过在 DOM 中渲染计算属性导致计算属性运行仅渲染元素。
<template>
<div>
<canvas id="myCanvas"></canvas>
</div>
<p v-show='false'>{{targetCounty}}</p>
</template>
我创建虚拟 DOM 元素只是为了获取已安装生命周期的计算属性(我认为这是非常糟糕的方法)
解决方法
您可以在 mounted()
钩子中使用 vm.$watch()
来观察商店的初始值的 getter:
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()
}
}
)
}
}
,
为什么不尝试创建一个显式返回值的函数,然后在mounted() 生命周期钩子中调用它,将其保存为常量。然后将该常量传递给您的 init 函数。
const targetCountry = this.$store.getters['parkingModule/byCounty'[this.countyname]
this.init(targetCountry)