[Vuejs]-How to prevent the data/method sharing of looped components in Vue.js

0👍

What happends is that both are using the data form the parent, and updating that same data.

It seems that you are making some kind of custom inputs. In that case in your child component you can use ‘value’ prop, and ‘input’ event, and in the parent user v-model to keep track of that especific data data.

Child component BaseInput.vue:

<template>
  <div>
    <input type="text" :value="value" @keyup="inputChanged">
  </div>
</template>

<script>
export default {
  props: ['value'],
  data () {
    return {

    }
  },
  methods: {
    inputChanged (e) {
      this.$emit('input', e.target.value)
    }
  }
}
</script>

And this is the code on the parent:

<template>
<div class="container">
    <div class="row">
        <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
            <base-input v-model="firstInputData"></base-input>
            <p>{{ firstInputData }}</p>
            <hr>
            <base-input v-model="secondInputData"></base-input>
            <p>{{ secondInputData }}</p>

        </div>
    </div>
</div>

<script>
import BaseInput from './BaseInput.vue'
    export default {
        components: {BaseInput},
        data() {
            return{
                firstInputData: 'You can even prepopulate your custom inputs',
                secondInputData: ''
            }
        }
    }
</script>

In the parent you could really store the diferent models in an object as properties, and pass that object to that “The another component” , pass them as individual props… pass an array ….

Leave a comment