简体   繁体   中英

Vue.js 2.x Change the value of the disabled attribute in the input element using the button

I have a lot of rows generated by a loop. Each of the rows has own 'input' with description and action buttons. One of this buttons is edit button responsible for changing 'disabled' attribute value. I do not have an idea how I should do it. Ok, I know that I should use $emit.

<template>
  <section id="tasks-list">
    <ul>
      <task
        v-for="(item, index) in filteredTasksList"
        v-bind:key="item.id"
        v-bind:index="index"
        v-bind:item="item"
        v-bind:tasks="tasks"
      />
    </ul>    
  </section>
</template>

and task component:

<template>
    <li :class="{checked: item.status}" class="task">
      <div class="task-description">
        <span>{{item.description}}</span>
        <input type="text" v-model="item.description" :disabled="true">
      </div>
      <div class="task-actions">
        <button class="btn-edit" v-on:click="disableItem()">{{translation.edit}}</button>
      </div>
    </li>
</template>

<script>
  export default {
    name: 'task',
    props: {
      item: { required: true },
      index: { reuqired: true },
      tasks: { required: true },
      search: { require: true }
    },
    methods: {
      disableItem(event){
        //part responsible for changing disabled attr
      }
    }
  }
</script>

Since disabled state and it's toggle handler are both inside <task> component, you can keep the logic inside that component. There is no need to $emit an event to a parent component, unless you want to manage state from parent.

Inside <task> component it can be achieved by using a boolean variable and changing it value on button click, via disableItem handler.

Input element should be changed to:

<input type="text" v-model="item.description" :disabled="isDisabled">

Add we should create a variable in component's data and update disableItem method as follows:

data () {
  return {
    isDisabled: false
  }
},
disableItem () {
  this.isDisabled = true
}

Also, it is not necessary to execute disableItem method in click handler, it can be just passed as a reference v-on:click="disableItem"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM