vue.js - 在 Vue 中,如果我需要在挂载生命周期钩子时使用 getter 中的状态怎么办?
问题描述
我尝试在挂载的生命周期挂钩期间使用来自 vuex 的数据。但是,在我从 vuex 获取数据之前,似乎已执行挂载的生命周期钩子。如何从 vuex 访问数据并在挂载的生命周期挂钩期间使用它?
代码如下。
我通过像这样的吸气剂带来数据。
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 元素只是为了获取已安装生命周期的计算属性(我认为这是非常糟糕的方法)
解决这个问题的解决方案是什么?
解决方案
您可以vm.$watch()
在mounted()
钩子中使用来观察商店的初始值:
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()
}
}
)
}
}
推荐阅读
- list - 按元组的第二个元素对元组列表进行排序,无需高阶函数或递归
- python - 如何在 python Telegram bot 的主要功能中获取 Telegram 用户的用户名?
- sip - 使用 ejabberd 进行 SIP 身份验证
- r - 如何在哑铃图中添加数据标签?
- mysql - SQL - 多 SELECT 和 GROUP BY 以获取表的 MIN(value)
- c - OpenSSL 中的时间范围是多少
- python - Pytorch 模型训练 CPU 内存泄漏问题
- json-api - JSON:API 中不区分大小写的过滤
- sql - 在 sql server 2016 中连接由分号分隔的特定列的值
- maven - 使用 Spock、maven 和 surefire 重新运行整个测试类