How to unbind an array copy in Vue.js

17,519

As Vue.js documentation says:

Under the hood, Vue.js attaches a hidden property __ob__ and recursively converts the object’s enumerable properties into getters and setters to enable dependency collection. Properties with keys that starts with $ or _ are skipped.

You can store your template array with name started from underscore sign:

  data: {
      testArray: [],
      _templateArray: [{ name: "TEST" }]
  },
  ready: function() {
      this.testArray = this.$data._templateArray;
  }

Or you if need it as a Vue.js object:

this.testArray = JSON.parse(JSON.stringify(this.templateArray));

The second case might be slow for big data.

Share:
17,519

Related videos on Youtube

Vaidas
Author by

Vaidas

Updated on September 15, 2022

Comments

  • Vaidas
    Vaidas about 1 year

    I am trying to copy one array to another and use this like the new array without any changes to old one:

    <div id="app">
        <div class="form-group">
           <label>Test input</label>
           <input v-model="testArray[0].name" type="text" class="form-control" placeholder="Input">
        </div>
        <br>
        <pre>testArray: {{ testArray[0] | json}}</pre>
        <pre>templateArray: {{ templateArray[0] | json  }}</pre>
    

    new Vue({
      el: '#app',
      data: {
          testArray: [],
          templateArray: [{name: "TEST"},], 
      },
      ready: function() {
          this.testArray = this.templateArray.slice(0);
        },
    });
    

    the issue is that then I am updating new array 'testArray' I also change old array 'templateArray'.

    The script in action: https://jsfiddle.net/4po1cpkp/7/

    Is there any way to create new array based on array template without directly binding it to template?

  • rinu
    rinu about 5 years
    this.testArray = this.templateArray.slice() seems to do the exact same thing.
  • Gustavo Straube
    Gustavo Straube over 4 years
    If it's the same as slice() it doesn't work for what the OP asked. It'll continue to be deeply attached to the original array, as mentioned in the question.