[英]Vuex: _this.$store is undefined
將Vuex添加到我的項目后,我無法訪問此。$ store存儲在任何組件中。 錯誤消息是
TypeError:_this。$ store未定義
我已經看過一堆已經試圖解決這個問題的問題,但據我所知,我做的一切都是正確的。 有人可以幫忙嗎? 我使用vue-cli webpack作為我的項目基礎
main.js:
import Vue from 'vue';
import resource from 'vue-resource';
import router from './router';
import store from './store/index.js';
import App from './App';
import Home from './components/Home';
import NavButton from './components/atoms/NavButton';
Vue.use(resource);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App, Home, NavButton },
template: '<App/>'
})
/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
isWriting: false,
isLoggedIn: false,
}
const getters = {
isWriting: state => {
return state.isWriting;
}
}
export default new Vuex.Store({
state,
getters,
});
App.vue
...
import NavBar from '@/components/organisms/NavBar';
export default {
name: 'App',
components: { NavBar },
created: () => {
console.log(this.$store.state.isLoggedIn); // THIS LINE
}
}
...
的package.json
...
"dependencies": {
"vue": "^2.5.2",
"vue-resource": "^1.3.6",
"vue-router": "^3.0.1",
"vuex": "^3.0.1"
},
...
解決了:
使用創建的胖箭頭不正確,應該created: function() {...}
當使用箭頭函數時,“this”將不是您期望的Vue實例,因為箭頭函數綁定到父上下文。 代替,
created() { //function body. "this" will be the Vue instance},
mounted() {//function body. "this" will be the Vue instance},
methods: { someFunc() {}, async someAsyncFunc {} }
將商店從app.js移動到/store/index.js后,我也遇到了這個問題
我不得不在提交state.store.myValue
store.myValue
更改為store.myValue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.