【问题标题】:How to access store in the mounted() method with NUXT.js?如何使用 NUXT.js 在mounted() 方法中访问存储?
【发布时间】:2019-06-21 18:22:53
【问题描述】:

我正在使用 Open Street Map 处理我的 NUXT.js 项目,我想在 mounted() 方法中访问 store。我收到错误,即未在 mounted() 方法命名空间中定义 store。如何访问它?

@/assets/js/utils.js

const utils = {

//...

updateMap(context) {
    let _context = context;

    const checkMapObject = setInterval(() => {
      if (_context.$refs.map) {
        _context.map = _context.$refs.map.mapObject;
        clearInterval(checkMapObject);

        //console.log(_context.map);

        if (process.browser) {
          L = require('leaflet');
          console.log("MAP OBJECT INITED");

          delete L.Icon.Default.prototype._getIconUrl;

          L.Icon.Default.mergeOptions({
            iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
            iconUrl: require('leaflet/dist/images/marker-icon.png'),
            shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
          });

          for (let marker of this.getMapMarkers(_context.store.state.pollingStations)) {
            L.marker(marker).addTo(_context.map)
          }
        }
      }
    }, 100);
  },

// ...

}

export default utils;

index.vue

<template>
   ...
</template>

<script>

...

import utils from '@/assets/js/utils'

export default {
  // ...

  mounted() {
    utils.updateMap(this)
  },

  // ...
}
</script>

我收到了这个错误:

Uncaught TypeError: Cannot read property 'state' of undefined

【问题讨论】:

  • 你能展示你的代码吗?
  • 对不起,你为什么不创建一个方法并从你的mounted中调用它呢?它对我有用,这是一个很好的做法。
  • @thanksd 我已经提供了我的资源。
  • 如果你正确设置了 Vuex,它需要是 _context.$store 而不是 _context.store
  • @thanksd 非常感谢!愚蠢的错误:)

标签: vue.js vuejs2 store nuxt.js


【解决方案1】:
  1. 首先,您应该能够在mounted() 中读取其Vue 组件实例。比如
mounted() {
  this.$store;
}
  1. 但问题是 this.$store 不能保证在调用 mounted() 时可用。

虽然我还在想办法,但我调试并注意到this.$store 不是立即可用,但会在mounted 的某个时间后可用。

截至今天,我找不到任何官方文档来描述 Vuex 在生命周期中的什么时候准备就绪。但我认为fetch 和它的状态看起来很有希望。我会尝试并报告。

【讨论】:

【解决方案2】:

由于 $store 没有立即启用并且您无法确定它,您可以测试它并仅在可用时使用它:

mounted() {
    while (!this.$store) {
      // Do nothing
    }
    this.$store.commit('xxxx/xxx');
},
  1. while 循环将一次又一次地循环,直到 this.$store 不再解析为 undefined
  2. 由于 while 循环不再循环,this.$store.commit('xxxx/xxx'); 行将被执行!!

借助这个小技巧,我可以在this.$store一可用时就使用它,直接借助mounted方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 2019-02-15
    • 2021-07-24
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多