xc Liu xc Liu - 2 months ago 36
Javascript Question

vuejs v-if condition for input model

i m just learn vue.js
and i want to display a table data.my opinion is when display mode the table just show. and when i click edit button of the line of the table, i want this line convert to model.

this is my code:
```

<table class="table table-bordered">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>pass</th>
<th>action</th>
</tr>
</thead>
<tbody>
<template v-for="data in apidata" track-by="$index">
<tr>
<td>{{$index + 1}}</td>
<td>
<div v-show="data.editmode"><input v-model="data.name"></div>
<div v-else>{{data.name}}</div>
</td>
<td>
<div v-if=data.editmode><input v-model="data.name"></div>
<div v-else>{{data.name}}</div>
</div>
</td>
<td>
<button v-on:click="remove($index)" class="btn btn-danger">remove</button>
<button v-on:click="edit(data)" class="btn btn-danger">edit</button>
</td>
</tr>
</template>
</tbody>
</table>

```
my data is like this

[{name:'test', pass:'1'}, {name:'test2', pass:'2'}]

i bind a edit()function to listen the click event.
edit: function(data){
alert(data.editmode);
data.editmode = true;
}


i think when i click .becuase the data.editmode will change to true.
this line will convert to input mode . but its useless.
i have tried v-if=data.editmode , v-if="data.editmode" ,v-show="data.editmode" , still got nothing
i dnt know why?

Answer

You just need to include editmode in your data declaration so that it is a reactive data item.

new Vue({
  el: 'body',
  data: {
    apidata: [{
      name: 'test',
      pass: '1',
      editmode: false
    }, {
      name: 'test2',
      pass: '2',
      editmode: false
    }]
  },
  methods: {
    edit: function(data) {
      data.editmode = !data.editmode;
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.27/vue.min.js"></script>
<table class="table table-bordered">
  <thead>
    <tr>
      <th>id</th>
      <th>name</th>
      <th>pass</th>
      <th>action</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="data in apidata">
      <td>{{$index + 1}}</td>
      <td>
        <div v-if="data.editmode">
          <input v-model="data.name">
        </div>
        <div v-else>{{data.name}}</div>
      </td>
      <td>
        <div v-if=data.editmode>
          <input v-model="data.pass">
        </div>
        <div v-else>{{data.pass}}</div>
      </td>
      <td>
        <button v-on:click="remove($index)" class="btn btn-danger">remove</button>
        <button v-on:click="edit(data)" class="btn btn-danger">edit</button>
      </td>
    </tr>
  </tbody>
</table>