【发布时间】:2021-07-12 11:19:11
【问题描述】:
我有一个使用商店 Vuex 的 vue 组件。但是我得到了一个
TypeError: Cannot read property 'token' of undefined
错误。我不明白为什么。这是我的代码:
在 main.js 中:
import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'
import router from './router';
import "./assets/css/tailwind.css";
import '@/assets/css/tailwind.css';
import store from './store';
Vue.config.productionTip = false;
Vue.use(Vuex);
new Vue({
router, store,
render: h => h(App),
}).$mount('#app');
在商店/indes.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
},
state: {
token: ''
}
})
在 GenericForm.vue 中:
methods: {
execute() {
console.log("GenericForm.vue")
if (this.inputFunction) {
this.inputFunction()
}
this.register()
},
register () {
console.log("register()")
try {
const response = AuthenticationService.register({
email: 'testss',
password: 'frgr'
})
this.$store.dispatch('setToken', response.data.token)
this.$store.dispatch('setUser', response.data.user)
this.$store.router.push({
name: 'songs'
})
} catch (error) {
console.log(error)
/*
this.error = error.response.data.error
*/
}
}
}
这行代码出现错误:
this.$store.dispatch
感谢任何帮助。
编辑:
AuthenticationService.js
import api from './api'
export default {
register (credentials) {
return api().post('register', credentials)
}
}
api.js
import axios from 'axios'
export default() => {
return axios.create({
baseURL: 'http://localhost:8081'
})
};
EDIT2:
新方法:
register: async () => {
console.log("register()")
const response = AuthenticationService.register({
email: 'testss',
password: 'frgr'
}).then((response) => {
console.log(response)
/* this.$store.dispatch('setToken', response.data.token)
this.$store.dispatch('setUser', response.data.user)*/
this.$store.router.push({
name: '/test'
})
});
}
我得到了错误
this.$store.router.push({
name: '/test'
})
行:
不过,响应会被记录下来。
【问题讨论】: