[Vuejs]-How to make the fields independent?

0๐Ÿ‘

โœ…

You should have profiles assigned to individual city

new Vue({
  el: '#app',
  data: {
  	cities: [],
  },
  
  mounted(){
  	this.cities.push({ 
        name: '',
        profiles: [
            { 
              name: '', 
              address: '' }
    		]
    	});
  },
  
  methods: {
  	addProfile(index) {
    	this.cities[index].profiles.push({
      	name: '',
        address: ''
      })
    },
    
    removeProfile(index) {
    	this.profiles.splice(index, 1);
    },
    
   	addCity() {
    	this.cities.push({ 
        name: '',
        profiles: [
            { 
              name: '', 
              address: '' }
    		]
    	})
    },
    
    removeCity(index) {
    	this.cities.splice(index, 1);
    },
  }
})
#app form {
  margin: 5px;
  width: 260px;
  border: 1px solid green;
  padding-top: 20px;
}

.column {
  padding: 5px;
}

.city {
  width: 280px;
  border: 1px solid red;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <div class="city">

    <form action="" v-for="(city, index) in cities">

      <div class="column" v-for="(profile, index) in city.profiles">
        <input type='text' v-model="profile.name" placeholder="Name">
        <input type='text' v-model="profile.address" placeholder="Address">
        <button type="button" @click="removeProfile">-</button>
      </div>

      <center><button type="button" @click="addProfile(index)">Add More People</button></center>

      <br><br><br>

    </form>
    <center>
      <button type="button" @click="addCity">Add Other City</button>
      <button type="button" @click="removeCity">Remove City</button>
    </center>

  </div>

</div>

0๐Ÿ‘

Profiles should be part of cities, like this

new Vue({
  el: '#app',
  data: {
    cities: [{
        name: '',
      profiles: [
            { name: '', address: '' }
        ]}
    ]
   },

  methods: {
    addProfile(city) {
        city.profiles.push({
        name: '',
        address: ''
      })
    },

   addCity() {
    this.cities.push(
    { name: '',
      profiles: [
            { name: '', address: '' }
        ]}
  )
},

    removeCity(index) {
        this.cities.splice(index, 1);
    },
  }
})

HTML:

<div id="app">

  <div class="city">

    <form v-for="city in cities">

      <div class="column" v-for="profile in city.profiles">
        <input type='text' v-model="profile.name" placeholder="Name">
        <input type='text' v-model="profile.address" placeholder="Address">
        <button type="button" @click="removeProfile">-</button>
      </div>

      <center>
        <button type="button" @click="addProfile(city)">Add More People</button>
      </center>

      <br><br><br>

  </form>
  <center>
    <button type="button" @click="addCity">Add Other City</button>
    <button type="button" @click="removeCity">Remove City</button>
  </center>

  </div>

  <div>

Leave a comment