javascript Vuex:无法读取未定义的属性“$store”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46335667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vuex: Cannot read property '$store' of undefined
提问by Karlom
I have set up a store in vue.js and can access the state parameters in the computed part of a compoenent:
我已经在 vue.js 中建立了一个商店,并且可以访问组件计算部分中的状态参数:
computed: {
BASE_URL () {
return this.$store.state.BASE_URL;
}
However, when I try to access the store in the methods of the same component:
但是,当我尝试在同一组件的方法中访问商店时:
methods: {
register: function () {
axios.post( this.BASE_URL + "/web/register", {
username: this.username,
password: this.password,
email: this.email
}).then(function(data){
this.$store.commit('saveToken', data.token);
console.log('token is set to:', this.$store.state.token)
});
}
},
I get this error at the console:
我在控制台收到此错误:
Uncaught (in promise) TypeError: Cannot read property '$store' of undefined
未捕获(承诺)类型错误:无法读取未定义的属性“$store”
I have also tried $storewithout thisbut get the same error.
我也试过$store没有this但得到同样的错误。
What is wrong here? How can I fix it?
这里有什么问题?我该如何解决?
回答by Jerico Pulvera
You're using a javascript function instead of an arrow function. Try this and it should work.
您使用的是 javascript 函数而不是箭头函数。试试这个,它应该可以工作。
methods: {
register () {
axios.post( this.BASE_URL + "/web/register", {
username: this.username,
password: this.password,
email: this.email
}).then( (data) => {
this.$store.commit('saveToken', data.token);
console.log('token is set to:', this.$store.state.token)
});
}

