vuejs,如何使用v-bind在v-for循环中绑定类

时间:2017-06-16 10:25:56

标签: vue.js

表格如下:

|平台|描述|备注|按钮|

当我点击设置此行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>

1 个答案:

答案 0 :(得分:1)

此问题可能是您的数据中不存在clicked属性,直到您通过方法添加它,并且Vue cannot detect that you added it

将您的代码更改为使用$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);
}
相关问题