Adding element to array that has v-model causes duplicate












1















I've got a list of text input-fields created through a v-for with a v-model to an array. I want to add elements to the array, and thus creating another input-field.



So far all works. The problem is that the new input-fields are somehow all assigned the same index (?) or something else is happening to cause them to display the same value.



I've made this jsfiddle to showcase what I mean. If you press the button twice and then try to edit one of the new input-boxes, then all the new input-boxes will get the edited value. I'd want only the edited input-box to show the input value.



I guess there is something I am overlooking here. Is there anyone who can help with this please?



Javascript:



new Vue({
el: '#app',
data: {
items: [{name: "one", id: 0}],
template: {
name: "two",
id: 2,
},
},
methods: {
addRow: function(){
this.items.push(this.template);
this.items[this.items.length - 1].id = Math.random();
}
}
})


HTML:



<script src="https://unpkg.com/vue"></script>

<div id="app">
<div v-for="(item,index) in items" :key="item.id">
<input v-model="item.name">
</div>
<button v-on:click="addRow">
Add row
</button>
<div>Array content: {{items}}</div>
</div>


Usage:
screenshot of what i'm getting










share|improve this question





























    1















    I've got a list of text input-fields created through a v-for with a v-model to an array. I want to add elements to the array, and thus creating another input-field.



    So far all works. The problem is that the new input-fields are somehow all assigned the same index (?) or something else is happening to cause them to display the same value.



    I've made this jsfiddle to showcase what I mean. If you press the button twice and then try to edit one of the new input-boxes, then all the new input-boxes will get the edited value. I'd want only the edited input-box to show the input value.



    I guess there is something I am overlooking here. Is there anyone who can help with this please?



    Javascript:



    new Vue({
    el: '#app',
    data: {
    items: [{name: "one", id: 0}],
    template: {
    name: "two",
    id: 2,
    },
    },
    methods: {
    addRow: function(){
    this.items.push(this.template);
    this.items[this.items.length - 1].id = Math.random();
    }
    }
    })


    HTML:



    <script src="https://unpkg.com/vue"></script>

    <div id="app">
    <div v-for="(item,index) in items" :key="item.id">
    <input v-model="item.name">
    </div>
    <button v-on:click="addRow">
    Add row
    </button>
    <div>Array content: {{items}}</div>
    </div>


    Usage:
    screenshot of what i'm getting










    share|improve this question



























      1












      1








      1








      I've got a list of text input-fields created through a v-for with a v-model to an array. I want to add elements to the array, and thus creating another input-field.



      So far all works. The problem is that the new input-fields are somehow all assigned the same index (?) or something else is happening to cause them to display the same value.



      I've made this jsfiddle to showcase what I mean. If you press the button twice and then try to edit one of the new input-boxes, then all the new input-boxes will get the edited value. I'd want only the edited input-box to show the input value.



      I guess there is something I am overlooking here. Is there anyone who can help with this please?



      Javascript:



      new Vue({
      el: '#app',
      data: {
      items: [{name: "one", id: 0}],
      template: {
      name: "two",
      id: 2,
      },
      },
      methods: {
      addRow: function(){
      this.items.push(this.template);
      this.items[this.items.length - 1].id = Math.random();
      }
      }
      })


      HTML:



      <script src="https://unpkg.com/vue"></script>

      <div id="app">
      <div v-for="(item,index) in items" :key="item.id">
      <input v-model="item.name">
      </div>
      <button v-on:click="addRow">
      Add row
      </button>
      <div>Array content: {{items}}</div>
      </div>


      Usage:
      screenshot of what i'm getting










      share|improve this question
















      I've got a list of text input-fields created through a v-for with a v-model to an array. I want to add elements to the array, and thus creating another input-field.



      So far all works. The problem is that the new input-fields are somehow all assigned the same index (?) or something else is happening to cause them to display the same value.



      I've made this jsfiddle to showcase what I mean. If you press the button twice and then try to edit one of the new input-boxes, then all the new input-boxes will get the edited value. I'd want only the edited input-box to show the input value.



      I guess there is something I am overlooking here. Is there anyone who can help with this please?



      Javascript:



      new Vue({
      el: '#app',
      data: {
      items: [{name: "one", id: 0}],
      template: {
      name: "two",
      id: 2,
      },
      },
      methods: {
      addRow: function(){
      this.items.push(this.template);
      this.items[this.items.length - 1].id = Math.random();
      }
      }
      })


      HTML:



      <script src="https://unpkg.com/vue"></script>

      <div id="app">
      <div v-for="(item,index) in items" :key="item.id">
      <input v-model="item.name">
      </div>
      <button v-on:click="addRow">
      Add row
      </button>
      <div>Array content: {{items}}</div>
      </div>


      Usage:
      screenshot of what i'm getting







      javascript arrays vue.js v-for v-model






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 19:11









      Boussadjra Brahim

      7,0633631




      7,0633631










      asked Nov 22 '18 at 18:48









      GnoppsGnopps

      274




      274
























          2 Answers
          2






          active

          oldest

          votes


















          1














          try



             this.items.push({
          name: "two",
          id: 2,
          });


          instead of this.items.push(this.template) because template property is reactive and it will affect other properties that use it



          check this fiddle






          share|improve this answer


























          • Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

            – Gnopps
            Nov 22 '18 at 19:23













          • you're welcome my bro

            – Boussadjra Brahim
            Nov 22 '18 at 19:25



















          3














          The problem here is that with array.push(declaredObject) you are adding a reference of template so every change will be reflected in all its references.



          You must add a new object with the same properties, you can achieve that in many ways, the more common is Object.assign({}, this.template) and the newest one is Destructuring objects {...this.template}. so in your case It should be this.items.push({...this.template})






          share|improve this answer





















          • 1





            thanks for these details +1

            – Boussadjra Brahim
            Nov 22 '18 at 19:27











          • Destructuring the template object seems to work great, thank you!

            – Gnopps
            Nov 22 '18 at 19:33











          • Glad it helped !

            – DobleL
            Nov 22 '18 at 19:37











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436682%2fadding-element-to-array-that-has-v-model-causes-duplicate%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          try



             this.items.push({
          name: "two",
          id: 2,
          });


          instead of this.items.push(this.template) because template property is reactive and it will affect other properties that use it



          check this fiddle






          share|improve this answer


























          • Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

            – Gnopps
            Nov 22 '18 at 19:23













          • you're welcome my bro

            – Boussadjra Brahim
            Nov 22 '18 at 19:25
















          1














          try



             this.items.push({
          name: "two",
          id: 2,
          });


          instead of this.items.push(this.template) because template property is reactive and it will affect other properties that use it



          check this fiddle






          share|improve this answer


























          • Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

            – Gnopps
            Nov 22 '18 at 19:23













          • you're welcome my bro

            – Boussadjra Brahim
            Nov 22 '18 at 19:25














          1












          1








          1







          try



             this.items.push({
          name: "two",
          id: 2,
          });


          instead of this.items.push(this.template) because template property is reactive and it will affect other properties that use it



          check this fiddle






          share|improve this answer















          try



             this.items.push({
          name: "two",
          id: 2,
          });


          instead of this.items.push(this.template) because template property is reactive and it will affect other properties that use it



          check this fiddle







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 19:03

























          answered Nov 22 '18 at 18:53









          Boussadjra BrahimBoussadjra Brahim

          7,0633631




          7,0633631













          • Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

            – Gnopps
            Nov 22 '18 at 19:23













          • you're welcome my bro

            – Boussadjra Brahim
            Nov 22 '18 at 19:25



















          • Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

            – Gnopps
            Nov 22 '18 at 19:23













          • you're welcome my bro

            – Boussadjra Brahim
            Nov 22 '18 at 19:25

















          Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

          – Gnopps
          Nov 22 '18 at 19:23







          Ah, of course: I forgot that with objects you don't clone, you just reference to the same object. Thank you for your help! I guess this means that I can't have a template-object but must create it on-the-fly in the function.?

          – Gnopps
          Nov 22 '18 at 19:23















          you're welcome my bro

          – Boussadjra Brahim
          Nov 22 '18 at 19:25





          you're welcome my bro

          – Boussadjra Brahim
          Nov 22 '18 at 19:25













          3














          The problem here is that with array.push(declaredObject) you are adding a reference of template so every change will be reflected in all its references.



          You must add a new object with the same properties, you can achieve that in many ways, the more common is Object.assign({}, this.template) and the newest one is Destructuring objects {...this.template}. so in your case It should be this.items.push({...this.template})






          share|improve this answer





















          • 1





            thanks for these details +1

            – Boussadjra Brahim
            Nov 22 '18 at 19:27











          • Destructuring the template object seems to work great, thank you!

            – Gnopps
            Nov 22 '18 at 19:33











          • Glad it helped !

            – DobleL
            Nov 22 '18 at 19:37
















          3














          The problem here is that with array.push(declaredObject) you are adding a reference of template so every change will be reflected in all its references.



          You must add a new object with the same properties, you can achieve that in many ways, the more common is Object.assign({}, this.template) and the newest one is Destructuring objects {...this.template}. so in your case It should be this.items.push({...this.template})






          share|improve this answer





















          • 1





            thanks for these details +1

            – Boussadjra Brahim
            Nov 22 '18 at 19:27











          • Destructuring the template object seems to work great, thank you!

            – Gnopps
            Nov 22 '18 at 19:33











          • Glad it helped !

            – DobleL
            Nov 22 '18 at 19:37














          3












          3








          3







          The problem here is that with array.push(declaredObject) you are adding a reference of template so every change will be reflected in all its references.



          You must add a new object with the same properties, you can achieve that in many ways, the more common is Object.assign({}, this.template) and the newest one is Destructuring objects {...this.template}. so in your case It should be this.items.push({...this.template})






          share|improve this answer















          The problem here is that with array.push(declaredObject) you are adding a reference of template so every change will be reflected in all its references.



          You must add a new object with the same properties, you can achieve that in many ways, the more common is Object.assign({}, this.template) and the newest one is Destructuring objects {...this.template}. so in your case It should be this.items.push({...this.template})







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 19:26









          Boussadjra Brahim

          7,0633631




          7,0633631










          answered Nov 22 '18 at 19:22









          DobleLDobleL

          1,529513




          1,529513








          • 1





            thanks for these details +1

            – Boussadjra Brahim
            Nov 22 '18 at 19:27











          • Destructuring the template object seems to work great, thank you!

            – Gnopps
            Nov 22 '18 at 19:33











          • Glad it helped !

            – DobleL
            Nov 22 '18 at 19:37














          • 1





            thanks for these details +1

            – Boussadjra Brahim
            Nov 22 '18 at 19:27











          • Destructuring the template object seems to work great, thank you!

            – Gnopps
            Nov 22 '18 at 19:33











          • Glad it helped !

            – DobleL
            Nov 22 '18 at 19:37








          1




          1





          thanks for these details +1

          – Boussadjra Brahim
          Nov 22 '18 at 19:27





          thanks for these details +1

          – Boussadjra Brahim
          Nov 22 '18 at 19:27













          Destructuring the template object seems to work great, thank you!

          – Gnopps
          Nov 22 '18 at 19:33





          Destructuring the template object seems to work great, thank you!

          – Gnopps
          Nov 22 '18 at 19:33













          Glad it helped !

          – DobleL
          Nov 22 '18 at 19:37





          Glad it helped !

          – DobleL
          Nov 22 '18 at 19:37


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436682%2fadding-element-to-array-that-has-v-model-causes-duplicate%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python