You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于ES6计算属性名函数声明与参数解构的技术疑问

Vuex代码中的ES6语法疑问解答

Hey there! Let's break down those two ES6 syntax questions you have about that Vuex mutation code—they're totally normal when you're getting used to modern JavaScript with Vuex. First, here's the code snippet we're talking about for reference:

[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++ 
  } 
}

1. 为什么用[types.ADD_TO_CART]声明函数,没写冒号?

This is two ES6 features working together: computed property names and shorthand object methods.

Back in ES5, if you wanted to define a method in an object, you'd write something like:

{
  ADD_TO_CART: function(state, payload) { /* ... */ }
}

But when you want to use a variable (or expression) as the property name instead of a hardcoded string, you wrap it in square brackets—this is the computed property name. Here, types.ADD_TO_CART is probably a string constant (like "ADD_TO_CART"), so using [types.ADD_TO_CART] lets us use that constant's value as the method name. This is super useful in Vuex because it keeps mutation types consistent across your app and prevents typos.

On top of that, ES6 lets you skip the function keyword and colon when defining object methods. So putting it all together, [types.ADD_TO_CART] (state, { id }) { ... } is just a shorter way to write:

{
  [types.ADD_TO_CART]: function(state, { id }) { /* ... */ }
}

2. 参数里的{ id }写法是什么意思?

That's object destructuring assignment, another handy ES6 feature. In Vuex, the second parameter to a mutation is the "payload"—usually an object that holds all the data you need for the mutation. For example, when you call this mutation, you might do something like:

this.$store.commit(types.ADD_TO_CART, { id: 456 })

Without destructuring, you'd have to write (state, payload) and then grab id with payload.id. But using { id } directly extracts the id property from the payload object and turns it into a standalone variable. It's just a cleaner way to write:

(state, payload) => {
  const id = payload.id;
  // rest of the code stays the same
}

If your payload had more properties (like { id, productName }), you could extract multiple variables in one go too.


内容的提问来源于stack exchange,提问作者Dr. Chocolate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:40:42