Vuex:无法读取未定义的 属性 '$store'
Vuex: Cannot read property '$store' of undefined
我已经在 vue.js 中设置了一个存储,并且可以访问组件的计算部分中的状态参数:
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)
});
}
},
我在控制台收到这个错误:
Uncaught (in promise) TypeError: Cannot read property '$store' of
undefined
我也试过 $store
没有 this
但得到同样的错误。
这里有什么问题?我该如何解决?
您正在使用 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)
});
}
我已经在 vue.js 中设置了一个存储,并且可以访问组件的计算部分中的状态参数:
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)
});
}
},
我在控制台收到这个错误:
Uncaught (in promise) TypeError: Cannot read property '$store' of undefined
我也试过 $store
没有 this
但得到同样的错误。
这里有什么问题?我该如何解决?
您正在使用 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)
});
}