vuejs,如何使用v-bind绑定v-for循环内的类

问题描述:

该表看起来像:vuejs,如何使用v-bind绑定v-for循环内的类

|平台|描述|评论|按钮|

当我点击一个前进按钮,设置此行的clicked=true,为什么按钮的类仍然是btn-primary(颜色:蓝)而不是btn-danger(颜色:红色)?

var app = new Vue({ 
 
     el: "#app", 
 
     data: { 
 
      grid_data: [], //ajax 
 
     }, 
 
     methods: { 
 
      "forward": function (url, index) { 
 
       this.grid_data[index].clicked = true; 
 
       openWindow(url); 
 
      } 
 
     } 
 
    })
<tr v-for="(item,index) in grid_data"> 
 
     <td>{{ item.platform }}</td> 
 
     <td>{{ item.description }}</td> 
 
     <td>{{ item.remark }}</td> 
 
     <td> 
 
      <button v-bind:class="[item.clicked ? 'btn-danger' : 'btn-primary', 'btn', 'btn-sm' ]" v-on:click="forward(item.url, index)">Forward</button> 
 
     </td> 
 
    </tr>

+0

Repproducing它jsFddle作品(https://jsfiddle.net/r_vamsi_krishna/dsezdx8f/3/)。 openWindow(url);'做什么? –

这里的问题可能是,直到你通过你的方法,并Vue公司cannot detect that you added it添加它的clicked属性不上你的数据存在。

更改您的代码使用$set

methods: { 
    "forward": function (url, index) { 
    this.$set(this.grid_data[index], 'clicked',true); 
    openWindow(url); 
    } 
}, 

工作example

此外,您可以避免传递索引。只需传递项目本身。

v-on:click="forward(item) 

而在你的方法,

"forward": function (item) { 
    this.$set(item, 'clicked',true); 
    openWindow(item.url); 
} 
+0

'setTimeout(()=> this.grid_data = gridData,500)'使用setTimeout解决。 (使用ajax的数据加载 - > new Vue({}) - > setTimeout) – wtf512

+0

@ wtf512我只使用'setTimeout'来模拟使用ajax调用填充数据。 – Bert