Home > Net >  How do show the inputs fields just for that specific iteration?
How do show the inputs fields just for that specific iteration?

Time:05-02

Trying to dynamically show the input fields just for a specific iteration - currently it shows the input fields for all of them. I have also prepared this stackblitz fiddle

Currently when i click ”add user to Stockholm”, all inputs fields show and all input fields are populated when I type the name of the new user.

<div
  v-for="(city, a) in cities"
  v-bind:key="city.name"
  style="margin-bottom: 30px"
>
  {{ city.name }}
  <div
    v-for="(user, b) in city.users"
    :
  >
    {{ user.name }} {{ b }}
    <button v-on:click="deleteUser(a, b)">Delelete</button>
    <button v-on:click="activateUser(a, b)">
      {{ user.active ? 'Unactive' : 'Active' }}
    </button>
  </div>

  <div v-if="addUser" style="margin-top: 10px">
    <input type="text" v-model="newUserName" placeholder="name" />&nbsp;
    <button v-on:click="addUserToArray(a)" >Add</button><br />
  </div>
  <br />
  <button v-on:click="addUser = !addUser">
    {{ addUser ? 'Close' : `Add user to ${city.name}` }}
  </button>
</div>

  data() {
    return {
      cities: [
        {
          name: 'Stockholm',
          users: [
            { name: 'Johan', active: true },
            { name: 'Adam', active: false },
            { name: 'Anders', active: false },
          ],
        },
        {
          name: 'New York',
          users: [
            { name: 'Andy', active: true },
            { name: 'Mitchell', active: false },
            { name: 'Steve', active: false },
          ],
        },
        {
          name: 'San Jose',
          users: [
            { name: 'Riana', active: true },
            { name: 'Rita', active: false },
            { name: 'Montgomery', active: false },
          ],
        },
      ],
      addUser: false,
      newUserName: '',
    };
  },

CodePudding user response:

Just replace boolean with index:

const app = Vue.createApp({
  data(){
    return {
      cities: [{name: 'Stockholm', users:[{name: 'Johan', active: true}, {name: 'Adam', active: false}, {name: 'Anders', active: false}]}, {name: 'New York', users:[{name: 'Andy', active: true}, {name: 'Mitchell', active: false}, {name: 'Steve', active: false}]}, {name: 'San Jose', users:[{name: 'Riana', active: true}, {name: 'Rita', active: false}, {name: 'Montgomery', active: false}]}],
      addUser: null,
      newUserName: ''
    }
  },
  computed: {
    activeUser: function(){
      return this.cities.map((city) => {
        return city.users.filter(function(q){
          return q.active
        })
      }).flat()
    }
  },
  methods: {
    //            
  • Related