简体   繁体   中英

Not able to spread an object with babel-plugin-transform-object-rest-spread added for vue cli 3 setup

This is partial code I am trying to get it working

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

So it will not have issue spreading array but when I pass spreading an object I will receive error of

TypeError: Invalid attempt to spread non-iterable instance

I added babel-plugin-transform-object-rest-spread plugin with config, yet, same error.

What is going on here?

Here is my repo to reproduce: https://github.com/adamchenwei/vue-hoc-playground check file /src/components/decorator/withCustomComponent.js Code:

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);
}

Doc about spread operator for object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals

AFAIK, you can't use spread operator to pass an object to a function as arguments; One of the reasons behind this is that Javascript function doesn't have native support of named parameters, which makes it impossible to match the parameters by name; One workaround could be to use destructuring syntax in your play function as follows:

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

And then you can call it with: play(myobj) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM