Javascript ES6函数语法?
我正在尝试调用我的同名存储:Javascript ES6函数语法?,javascript,vue.js,vuejs2,vuex,Javascript,Vue.js,Vuejs2,Vuex,我正在尝试调用我的同名存储: methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); } 这会导致错误: Uncaught TypeError: Cannot read property 'toggleActive' of undefined 进行以下工作: close: function() {
methods: {
...mapActions('Modal', [
'toggleActive',
]),
close: () => {
this.toggleActive();
}
这会导致错误:
Uncaught TypeError: Cannot read property 'toggleActive' of undefined
进行以下工作:
close: function() {
this.toggleActive();
}
如何将ES6函数语法与vue/vuex结合使用?您使用的是箭头函数。箭头函数在定义它们的上下文中关闭
this
,而不是像调用function
函数那样设置。例如:
// Whatever `this` means here
var o = {
foo: () => {
// ...is what `this` means here when `foo` is called
}
};
您可能只想改用方法语法:
methods: {
// (I'm using a simple method for toggleActive just for clarity; if you're
// transpiling with something that understands rest notation for
// objects, your `mapActions` thing is probably fine *provided* that
// the functions it creates aren't also arrow functions
toggleActive() {
// ...
},
close() {
ths.toggleActive();
}
};
请注意,这取决于所有常见的
这类内容。您使用的是箭头函数。箭头函数在定义它们的上下文中关闭this
,而不是像调用function
函数那样设置。例如:
// Whatever `this` means here
var o = {
foo: () => {
// ...is what `this` means here when `foo` is called
}
};
您可能只想改用方法语法:
methods: {
// (I'm using a simple method for toggleActive just for clarity; if you're
// transpiling with something that understands rest notation for
// objects, your `mapActions` thing is probably fine *provided* that
// the functions it creates aren't also arrow functions
toggleActive() {
// ...
},
close() {
ths.toggleActive();
}
};
请注意,这取决于所有常见的这类内容。谢谢,我已经查看了您的链接和编辑过的答案,但我仍然感到困惑,因为箭头函数中的“this”应该指vuex命名空间状态?@panthro:他们为什么会这样做?同样,它们关闭此
,就像关闭其他变量一样。(如果你没有看到我上面的foo
示例,点击刷新。)我检查了你的foo示例,啊,那么“this”在类外的意思是“this”?@panthro:我不能评论我看不到的代码,你在问题中没有提供太多上下文,只是对象初始值设定项的部分内部。但是无论这个
在对象初始值设定项的范围内是什么,当调用关闭
时,这个
就是什么。谢谢,我已经查看了你的链接和你编辑过的答案,我仍然感到困惑,因为箭头函数是“this”inside应该指的是vuex名称空间的状态?@panthro:他们为什么要这样做?同样,它们关闭此
,就像关闭其他变量一样。(如果你没有看到我上面的foo
示例,点击刷新。)我检查了你的foo示例,啊,那么“this”在类外的意思是“this”?@panthro:我不能评论我看不到的代码,你在问题中没有提供太多上下文,只是对象初始值设定项的部分内部。但是无论this
在对象初始值设定项的作用域中是什么,都是调用close
时的this
的作用域。