【问题标题】:Not able to spread an object with babel-plugin-transform-object-rest-spread added for vue cli 3 setup无法使用为 vue cli 3 设置添加的 babel-plugin-transform-object-rest-spread 传播对象
【发布时间】:2019-03-22 11:05:23
【问题描述】:

这是我试图让它工作的部分代码

const myarr = [
        {a: 'haha',},
        {b: 'yoyo',}
      ];
      const myobj = {
        a: 'some',
        b: 'kind',
      };
      console.log(myarr);
      play(...myobj);
      console.log(props);

所以它不会有传播数组的问题,但是当我通过传播一个对象时,我会收到错误

TypeError:传播不可迭代实例的尝试无效

我在配置中添加了babel-plugin-transform-object-rest-spread 插件,但是,同样的错误。

这是怎么回事?

这是我要复制的回购:https://github.com/adamchenwei/vue-hoc-playground 检查文件/src/components/decorator/withCustomComponent.js 代码:

export default function withCustomComponent(InnerComponent) {
  return {
    mounted() {
      console.log('withCustomComponent is mounted');
    },
    render() {
      const myarr = [
        {a: 'haha',},
        {b: 'yoyo',}
      ];
      const myobj = {
        a: 'some',
        b: 'kind',
      };
      console.log(myarr);
      play(myobj);
      console.log(props);
      return <InnerComponent
        class="myinner"
        data-event="load"
        />;
    }
  }
}

export const WithCustom = {
  name: 'WithCustom',
  render() {
    const Slott = this.$slots.default[0];
    // return  <Slott />;
    return this.$slots.default[0];
    // return <h1>slott</h1>;
  }
};

function play({a,b}) {
  console.log('play')
  console.log(JSON.stringify(a));
  console.log(`${a} ${b}`);
}

function fakeCall(params, callback) {
  setTimeout(() => {
    callback('https://avatars0.githubusercontent.com/u/6078720?s=200&v=4')
  }, 1000);
}

关于对象扩展运算符的文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals

【问题讨论】:

    标签: javascript vue.js babeljs vue-cli spread-syntax


    【解决方案1】:

    AFAIK,您不能使用扩展运算符将对象作为参数传递给函数;这背后的原因之一是 Javascript 函数没有对命名参数的原生支持,这使得无法通过名称匹配参数;一种解决方法是在 play 函数中使用解构语法,如下所示:

    function play({ a, b }) {
      console.log('play')
      console.log(JSON.stringify(a));
      console.log(`${a} ${b}`);
    }
    

    然后你可以调用它:play(myobj)

    【讨论】:

    • 感谢您的回答,我想我一定错过了您的回答,因为文档表明我应该能够在新配置 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 中传播对象,如果有什么我可能误解了你的意思说什么?
    • 是的,对象的传播运算符存在,但它仅用于传播属性。来自文档:ECMAScript 提案的 Rest/Spread Properties(第 4 阶段)将扩展属性添加到对象字面量。 即从现有对象创建新对象,这与将对象值作为参数传递给函数。
    • 啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊所以我应该做 ({a,b}) 而不是 (a,b) ,这是有道理的!谢谢!
    • 所以我想我做过的 {...props} 根本不应该工作...酷!
    • @halfer 我确实查看了withCustomComponent.js 以了解play 函数是如何定义的。如果 OP 可以在问题中包含函数定义以使其更完整,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 2020-05-28
    • 2019-06-12
    • 2021-03-22
    • 2017-08-18
    • 1970-01-01
    • 2019-04-19
    • 2016-09-05
    相关资源
    最近更新 更多