在我正在进行的教程中找到了这个。 这是ES6。
我只是不确定到底是怎么回事。即,使用数组声明函数(?)的方式。将结构声明为函数的冒号在哪里?
[types.ADD_TO_CART] (state, { id })
参数声明中的括号是什么?
(state, { id })
这是教程。
https://medium.com/@connorleech/build-a-shopping-cart-with-vue-2-and-vuex-5d58b93c513f
[types.ADD_TO_CART] (state, { id }) {
const record = state.added.find(p => p.id === id)
if (!record) {
state.added.push({
id,
quantity: 1
})
} else {
record.quantity++
}
}
答案 0 :(得分:2)
您必须在不使用:
的情况下在类上定义方法:
class Example {
method() {
console.log('here')
}
}
new Example().method()
使用ES6计算属性名称,您可以使该方法的名称为动态:
const name = 'method'
class Example {
[name]() {
console.log('here');
}
}
new Example()[name]()
就({ id })
部分而言,id
表示使用解构的动态方法的参数提取的属性:
// this
[types.ADD_TO_CART](state, obj) => {
let id = obj.id;
}
// can be abbreviated to this
[types.ADD_TO_CART](state, { id }) => {
}
例如:
const name = 'method'
class Example {
[name]({
id
}) {
console.log(id);
}
}
new Example()[name]({
id: 'example'
})
答案 1 :(得分:1)
使用ES2015,您可以获得两个对象文字的新功能:
// Computed object properties
const foo = 'bar'
const myObj = {
[foo]: 'hello world'
}
// Shorthand method definitions:
const mySecondObj = {
myMethod () {
// code...
}
}
示例中的代码似乎将两者结合在一起。
此外,ES2015为您提供object destructuring,用于参数 - 因此是大括号。
Check MDN了解有关新语法功能的更多详细信息。