[Vuejs]-How to append input data to props in Vue.js

0👍

You should check out the docs for splice.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

EDIT:

Just change

data() {
    return {             
        form: new Form({                    
            session: '',     
            tags: this.tags.splice(1, 0, this.session)               
        })                             
    }
},

to

data() {
    this.tags.splice(1, 0, this.session);
    return {             
        form: new Form({                    
            session: '',     
            tags: this.tags               
        })                             
    }
},

0👍

splice providing elements at the end, adds the elements to the array, at the given index you provided as first parameter,

If you provide the second argument too, different from 0, it replaces the elements.

But in any case, it returns an array of the deleted elements, which in case of adding is an empty array.

So when you do:

this.tags.splice(1, 0, this.session)   

It returns an empty array, and you assign an empty array to tags prop.

You could fix the issue doing something like:

export default {
    props: ['tags'],

    data() {
        return {             
            form: new Form({                    
                session: '',     
                tags: Array.isArray(this.tags.splice(1, 0, this.session)) ? this.tags : []               
            })                             
        }
    },      

    methods: {        

    }
}

But that’s pretty a workaround because your this.session exists only inside the Form you are creating.

A better approach could be something like:

data() {
  const form = new Form({ session: '', tags: this.tags});
  form.tags.splice(1, 0, form.session);   
  return {
    form
  }
},    

0👍

Guess what, I managed to append the select input to the bloody props array by setting v-on:input=”SelectChange” on the tag. And then in my method I put:

selectChange() {            
        this.form.tags = Array.isArray(this.form.tags.splice(1, 0, this.form.session)) ? this.form.tags : [];
      },

It works, but the problem now is if you select several options it appends each to the array instead of replacing them.

0👍

Got it working in the end. Thank you all for your replies and help.

This is the code snippet that works for me:

selectChange() { 
          var arrcount = this.form.tags;

          if(arrcount.length !== 2) {
            this.form.tags.splice(2,1);
          }
          this.form.tags.push(this.form.session);
        },

Leave a comment