Javascript Vuex:无法读取属性'$商店';未定义的
我在vue.js中设置了一个存储,可以访问组件计算部分的状态参数:Javascript Vuex:无法读取属性'$商店';未定义的,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我在vue.js中设置了一个存储,可以访问组件计算部分的状态参数: computed: { BASE_URL () { return this.$store.state.BASE_URL; } 但是,当我尝试使用同一组件的方法访问存储时: methods: { register: function () { axios.post( this.BASE_URL + "/web/register", { username
computed: {
BASE_URL () {
return this.$store.state.BASE_URL;
}
但是,当我尝试使用同一组件的方法访问存储时:
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)
});
}
},
我在控制台上收到此错误:
未捕获(承诺中)TypeError:无法读取的属性“$store”
未定义
我也尝试了$store
,但没有这个
,但得到了相同的错误
这里怎么了?如何修复它?您使用的是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)
});
}
您是否已在应用程序中注册vuex<代码>Vue。使用(Vuex)是的,我使用了。正如我所说的,vuex可以在组件的
computed
部分访问,但不能在方法的promise.facility中访问。这就解决了问题。但是为什么我不能在promise中使用vanilla JS呢?函数有自己的“this”实例,所以当你调用它时,你得到的是函数的实例,而不是vue实例。在普通javascript中,典型的解决方案是在函数外部创建一个临时变量,然后在函数内部使用它。e、 g var self=这个;register:function(){self.$store.commit();}仅供参考,arrow函数也是“普通”JavaScript。@Phil感谢您提供的信息,我不知道我从中学习的教程在这方面是错误的。