【发布时间】: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