Luco
Luco

Reputation: 49

I want to show only one input clicked (on vue.js)

I would like to show an input on the click, but being in a for loop I would like to show only the clicked one

<div v-for="(todo, n) in todos">
    <i class="fas fa-minus ml-2"></i>
    <li class="mt-2 todo">
        {{ todo }}
    </li>
    <li class="button-container">
        <button class="ml-1 btn btn-primary rounded-circle btn-sm" v-if="isHidden" v-on:click="isHidden = false"><i
                class="THIS-CLICK"></i></button>
        <input class="ml-5 border border-primary rounded" v-if="!isHidden" v-model="todo">
        <button class="ml-1 btn btn-success rounded-circle btn-sm" v-if="!isHidden" v-on:click="isHidden = true"
            @click="modifyTodo(n, todo)"><i class="far fa-save"></i></button>
    </li>
</div>

I would like that on clicking on THIS-CLICK, only one input (that of the button clicked) is visible, but being in a for loop I don't know if it can be done

Upvotes: 2

Views: 1048

Answers (1)

S&#248;lve
S&#248;lve

Reputation: 4406

I would suggest to change the structure a bit in your app. You can clean up your code a lot by using v-if inside the button instead of two different buttons.

Also, moving as much javascript out from the markup as possible is a good practice.

I have an example below where this is done.

Regarding your question, you would have to add the key to each todo item.

new Vue({
  el: "#app",
  data() {
    return {
      todos: [{
          name: 'wash hands',
          isHidden: true
        },
        {
          name: 'Stay home',
          isHidden: true
        }
      ],
    };
  },

  methods: {
    toggleTodo(n, todo) {
      const hidden = todo.isHidden;
      
      if (hidden) {
        this.modifyTodo(n, todo);
        todo.isHidden = false;
      } else {
        todo.isHidden = true;
      }
    },
    
    modifyTodo(n, todo) {
      //Some logic...
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-for="(todo, n) in todos">
    <i class="fas fa-minus ml-2"></i>
    
    <li class="mt-2 todo">
      {{ todo.name }}
    </li>
    
    <li class="button-container">
      <input class="ml-5 border border-primary rounded" v-if="!todo.isHidden" v-model="todo.name">
      
      <button @click="toggleTodo(n, todo)">
        <i v-if="todo.isHidden" class="THIS-CLICK">click-this</i>
        <i v-else class="far fa-save">save</i>
      </button>     
    </li>
  </div>

</div>

If you cannot do this, you could go with adding a new key to data like: hiddenTodos that would be an array of ids/a unique identifier to the todo you selected to hide.

in the template, it would be something like this:

<button @click="hiddenTodos.push(todo)">
...
<div v-if="hiddenTodos.includes(todo)"

Upvotes: 3

Related Questions