首页 > 解决方案 > 使用传播运算符获取操作的原因是什么?

问题描述

当我们只有一个属性时,为什么我们可以不使用扩展运算符来获取操作?当我们拥有多个属性时,为什么不使用扩展运算符就无法执行操作?

换句话说:

为什么这是真的

methods:{
mapActions(["fetchImages"])
},

但是这是错误的:

methods:{
mapActions(["fetchImages"]),
a:10
},

标签: vue.jsvuex

解决方案


因为mapActions会返回一个对象,如果直接把对象返回给方法,就意味着对象就是方法。但是如果你想给方法添加更多的函数,你必须合并它们,因为我们使用了 spred 操作符。

1)这不起作用,您没有任何 mapActions 返回的对象的键

methods:{
  mapActions(["fetchImages"])
},

//result
{{fetchImages: function(){...}}}

2) 方法将是一个对象,里面有 fetchImages 函数

methods: mapActions(["fetchImages"])
// result
{fetchImages: function () {...}}

3) 方法将是一个合并了 'fetchImages' 函数和 'a' 函数的对象

methods: {
...mapActions(["fetchImages"]),
a: function () { return 'a' }
}
// result
{fetchImages: function () {...}, a: function() {...}}

4)这不是 goig 工作,因为我们再次尝试向我们的方法对象添加一个没有键的对象

methods: {
mapActions(["fetchImages"]),
a: function () { return 'a' }
}

//result
{{fetchImages: function() {...}}, a: function(){...}}

5)对于这项工作,或者我们使用扩展运算符或为 mapActions 结果对象添加一个键,如下所示

methods: {
  actions:mapActions(["fetchImages"]),
  a: function () { return 'a' }
}

//result
{ actions: { fetchImages: function() {}}, a: function(){...}}


推荐阅读