laso
laso

Reputation: 51

VueJS - How to Enable/Disable a specific input in a v-for loop

I need to enable/disable specific inputs on button click.

My problem here is when I click my button, ALL the inputs enable/disable I am having a hard time targeting a single one. I use props “articles” which returns the “id”, “title” and “body” of my articles.

<div v-for="(article, index) in articles" v-bind:key="article.id">
  <div class="flex">
    <div class="flex-1 px-2 py-2">
      <input
        v-model="article.title"
        type="text"
        :disabled="isDiabled"
        class="w-full disabled:opacity-75 bg-gray-300 focus:bg-white"
      />
    </div>
    <div class="flex-1 px-2 py-2">
      <input
        v-model="article.body"
        type="text"
        :disabled="isDiabled"
        class="w-full disabled:opacity-75 bg-gray-300 focus:bg-white"
      />
    </div>
    <div class="px-2 py-2">
      <button
        class="px-2 py-2 border-gray-400 bg-gray-800 rounded text-white hover:border-gray-300 items-end"
        @click="enableEdit"
      >
        Edit
      </button>
    </div>
  </div>
</div>

<script>
  export default {
    props: ["articles"],

    data() {
      return {
        isDiabled: true,
      };
    },

    methods: {
      enableEdit() {
        this.isDiabled = false;
      },
    },
  };
</script>

Every article has his own button and I want only the two inputs of the button that is clicked to be enabled/disabled and not all of them.

Upvotes: 1

Views: 1709

Answers (2)

daniel
daniel

Reputation: 1162

As being pointed you need to add also that property to your articles... of course you don't need to do this in the database, still using it as a property you need also to emit this change of the flag to the parent.

You could also use a local version of the articles where you add also this isDisabled property, you fill this new variable at the creation of the component based of course on the property you received from the parent,

created(){
  this.local_articles = this.articles.map(e => { 
        return {...e, isDisabled: true} }
  )
},

this way you don't need to propagate nothing to the parent as you can handle all internally.

This fiddle gives a solution to your problem.

Upvotes: 1

Liel Fridman
Liel Fridman

Reputation: 1198

Make a boolean property for each article, then change the binding of disabled to that property.

Upvotes: 1

Related Questions