[英]How can i fix “this is undefined” in VueJS?
The line this.$store.commit('disconnect');
行
this.$store.commit('disconnect');
is causing a "this is undefined" error, what can i do?导致“这是未定义”错误,我该怎么办?
store/index.js:存储/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
}
}
index.vue索引.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>
If i delete the line of the commit
in the index.vue
file, it works fine, but i need to use it so how can i fix this?如果我删除
index.vue
文件中的commit
行,它工作正常,但我需要使用它,那么我该如何解决这个问题?
Thanks again再次感谢
In the callback context, this
tense to callback itself.在回调上下文中,
this
时态回调本身。 That's why you are getting the error.这就是您收到错误的原因。 You should replace it with,
您应该将其替换为,
self.$store.commit('disconnect');
where the self
holds the actual context of Vue. self
持有 Vue 的实际上下文。 Here is the explanation,这里是解释,
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.