阿波羅的戰車
2022-11-03 10:15:33
TypeError: Cannot read property 'dispatch' of undefined嘗試提交 Login.vue 表單時出現錯誤。我將我的更改function()為只是data()等,就像建議的 SO 答案一樣,但這并沒有幫助......index.js:import Vue from 'vue';import Vuex from 'vuex';import auth from './store/auth.module.js';Vue.use(Vuex);export default new Vuex.Store({ //plugins: [createPersistedState({ storage: sessionStorage })], state: { }, mutations: { }, actions: { }, modules: { auth }})主.js:import Vue from 'vue'import App from './App.vue'import router from './router';import store from './store/auth.module';import "./assets/css/tailwind.css";import '@/assets/css/tailwind.css';Vue.config.productionTip = false;new Vue({ router, store, render: h => h(App),}).$mount('#app');auth-header.js:export default function authHeader() { let user = JSON.parse(localStorage.getItem('user')); if (user && user.accessToken) { return { Authorization: 'Bearer ' + user.accessToken }; } else { return {}; }}user.service.js:import axios from 'axios';import authHeader from './auth-header';const API_URL = 'localhost:8088/testproject/api/users';class UserService { getPublicContent() { return axios.get(API_URL + '/all'); } getUserBoard() { return axios.get(API_URL + '?role=user', { headers: authHeader() }); } getModeratorBoard() { return axios.get(API_URL + '?role=mod', { headers: authHeader() }); } getAdminBoard() { return axios.get(API_URL + '?role=admin', { headers: authHeader() }); }}export default new UserService();
4 回答

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
猜測一下,我會說問題出在main.js
// main.js
import store from './store/auth.module';
這似乎是在導入您的一個商店模塊,它不會是一個Vuex.Store實例。
在main.js,你需要導入商店index.js
// main.js
import store from './index.js'
通過不導入store/index.js,您也錯過了所有重要的
Vue.use(Vuex)

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
你能檢查一下你是否正確地導入了 Vuex 嗎?
我覺得 phil 的回答是正確的,但這里還有一些可能有助于解決問題的額外閱讀:cannot read property 'dispatch' of undefined in Vuex

慕容708150
TA貢獻1831條經驗 獲得超4個贊
請檢查您的文件夾結構是否如下所示。
存儲文件夾->(包含)auth.module,index.js(您提到的第一個代碼片段)。
現在將商店導入到main.js
如下所示。
import store from './store'
現在你剩下的代碼應該可以工作了。

MYYA
TA貢獻1868條經驗 獲得超4個贊
將此行添加到您的main.js文件中:
import store from '../yourPath';
vue.$store = store
這將全局設置存儲對象。所以你可以通過使用從任何組件訪問它this
添加回答
舉報
0/150
提交
取消