首页 > 解决方案 > 在 Vue 中,如果我需要在挂载生命周期钩子时使用 getter 中的状态怎么办?

问题描述

我尝试在挂载的生命周期挂钩期间使用来自 vuex 的数据。但是,在我从 vuex 获取数据之前,似乎已执行挂载的生命周期钩子。如何从 vuex 访问数据并在挂载的生命周期挂钩期间使用它?

代码如下。

  1. 我通过像这样的吸气剂带来数据。

     computed:{
     targetCounty(){
     return this.$store.getters['parkingModule/byCounty'][this.countyname]
     }
    
  2. 然后我需要通过 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)
    
     },
    
  3. 这个 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 元素只是为了获取已安装生命周期的计算属性(我认为这是非常糟糕的方法)

解决这个问题的解决方案是什么?

标签: vue.jslifecycle

解决方案


您可以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()
        }
      }
    )
  }
}

演示


推荐阅读