[Vuejs]-Toggle form inside v-for using vue.js

2👍

There is only 1 reactive variable show. Setting it to true while all form is using v-if="show", will show everything.

You can set show to something that each form uniquely have. For example, its text, and perform a v-if using its text.

demo: https://jsfiddle.net/jacobgoh101/umaszo9c/

change v-if="show" to v-if="show === todo.text"

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="(todo,key) in todos">
      <p>
        {{ key+1 }} - {{ todo.text}} <span @click="toggle(todo)"><b>Contact</b></span>
        <div v-if="show === todo.text">
          <hr />
          <p>
            <label>Message</label>
            <input type="text">
          </p>
          <hr />
        </div>
      </p>
    </li>
  </ol>
</div>

change toggle method

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript"
      },
      {
        text: "Learn Vue"
      },
      {
        text: "Play around in JSFiddle"
      },
      {
        text: "Build something awesome"
      }
    ],
    show: ''
  },
  methods: {
    toggle: function(todo) {
      if (this.show === todo.text)
        this.show = false
      else
        this.show = todo.text
    }
  }
})

1👍

property “show” should be a prop of todo,not prop of data

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript"
      },
      {
        text: "Learn Vue"
      },
      {
        text: "Play around in JSFiddle"
      },
      {
        text: "Build something awesome"
      }
    ].map(o=>({...o,show:false}))
  },
  methods: {
    toggle: function(todo) {
      todo.show = !todo.show
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="(todo,key) in todos">
      <p>
        {{ key+1 }} - {{ todo.text}} <span @click="toggle(todo)"><b>Contact</b></span>
        <div v-if="todo.show">
          <hr />
          <p>
            <label>Message</label>
            <input type="text">
          </p>
          <hr />
        </div>
      </p>
    </li>
  </ol>
</div>
👤jacky

Leave a comment