我想用store
读取router
中的数据,但它不起作用
我尝试了三种方法,但没有人是对的。
试着用
// ReferenceError: store is not defined
console.log(store.state);
// ReferenceError: $store is not defined
console.log($store.state);
// TypeError: Cannot read property '$store' of undefined
console.log(this.$store.state);
如果我在App.vue
中使用它,它可以工作。
App.vue
export default {
created() {
console.log(this.$store.state.user);
},
}
我该怎么办?
存储/index.js
state: {
user: {
loggedIn: false,
data: null
},
},
路由器/index.js
router.beforeEach((to, from, next)=>{
// console.log(store.state);
// console.log($store.state);
console.log(this.$store.state);
// if(this.$store.state.user.loggedIn){
// next('/login');
}else
next();
})
发布于 2020-08-16 16:56:48
试着导入它:
import store from '../store/';
然后按以下方式使用:
store.state
确保在store/index.js
中导出它
export default new Vuex.Store({
//config
});
发布于 2020-08-16 16:58:04
您可以在$store
中使用App.vue的原因是您在app.js中导入了store.js并添加到Vue实例中。如果您想在另一个js文件中使用您的vuex存储,只需导入它。
import Store from './store.js';
console.log(Store);
https://stackoverflow.com/questions/63439507
复制相似问题