[英]How can i fix “this is undefined” in VueJS?
行this.$store.commit('disconnect');
導致“這是未定義”錯誤,我該怎么辦?
存儲/index.js:
export const state = () => ({
log: false,
user: {token: null, id: null, username: null, email: null, created_at: null, pseudo: null}
})
export const mutations = {
connect (state) {
state.log = true
},
disconnect (state) {
state.log = false,
state.user.id = null,
state.user.username = null,
state.user.email = null,
state.user.created_at = null,
state.user.pseudo = null
}
}
索引.vue
<script>
import axios from "axios";
methods: {
async login() {
var self = this;
const auth_res = axios({
method:'post',
url:'http://127.0.0.1:8000/v2.0/auth',
data:{
username: this.username,
password: this.password
}
}).then(function(res){
this.$store.commit('disconnect');
self.$router.push('/');
}).catch(function (erreur) {
console.log(erreur);
});
}
}
}
</script>
如果我刪除index.vue
文件中的commit
行,它工作正常,但我需要使用它,那么我該如何解決這個問題?
再次感謝
在回調上下文中, this
時態回調本身。 這就是您收到錯誤的原因。 您應該將其替換為,
self.$store.commit('disconnect');
self
持有 Vue 的實際上下文。 這里是解釋,
methods: {
async login() {
var self = this; // You got the context of the method which belongs to Vue
const auth_res = axios({
method:'post',
...
}).then(function(res){
self.$store.commit('disconnect'); // The self.$store is now avaialable in callback
self.$router.push('/');
}).catch(function (erreur) {
...
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.