[英]Vue.js weird rendering with class binding
So basically I have an html table with a v-for
that loops over an array of objects, nothing complicated here. 所以基本上我有一个带有
v-for
的html表,它循环遍历一个对象数组,这里没什么复杂的。 When the user clicks on a row, it toggles the selected
property of the object "linked" to the given row. 当用户单击某一行时,它会切换“链接”到给定行的对象的
selected
属性。
Now, I also setup a simple class-binding with v-bind:class="{'active': n.selected}"
where n
is my object, but it doesnt update. 现在,我还使用
v-bind:class="{'active': n.selected}"
设置了一个简单的类v-bind:class="{'active': n.selected}"
其中n
是我的对象,但它没有更新。 Now what is more weird is that I use the webpack template from the vue-cli, and when I : 现在更奇怪的是我使用vue-cli中的webpack模板,当我:
F5
which triggers the webpack hot-reload F5
,触发webpack热重载 The selected rows suddenly get the active
class, as the CSS says so, until the webpack hot-reload has regenerated the page. 所选行突然得到
active
类,正如CSS所说,直到webpack热重载已重新生成页面。
Here is my code : 这是我的代码:
<tr
v-for="n in node.children"
track-by="id"
v-on:click="toggleElement(n)"
v-bind:class="{'active': n.selected}">
<td>
<i class="icons">
<i class="folder yellow icon"></i>
</i>
</td>
<td><a v-on:click.stop="getLevel(n.id)">{{ n.name }}</a></td>
<td><span v-if="n.modification_date">{{ n.modification_date | moment "calendar"}}</span><span v-else>-</span></td>
<td><span v-if="n.size">{{ n.size }}</span><span v-else>-</span></td>
And for the javascript method 而对于javascript方法
toggleElement: function(element) {
element.selected = !!(element.selected === undefined || !element.selected);
},
Now some more details, the objects are being retrieved by an ajax call, and the selected
property doesnt exist from the start. 现在更多细节,通过ajax调用检索对象,并且
selected
属性从一开始就不存在。
Any advice or solution ? 任何建议或解决方案? Thanks a lot!
非常感谢!
First, do not forget to add the closing </tr>
in your code. 首先,不要忘记在代码中添加结束
</tr>
。
Second, you can not add new attributes on objects after creating them with VueJS. 其次,使用VueJS创建对象后,无法在对象上添加新属性。
If when creating the element, its attribute selected
was undefined, then VueJS will not add the getter/setter on it and changing it won't update the interface. 如果在创建元素时,其
selected
属性未定义,则VueJS将不会在其上添加getter / setter,并且更改它将不会更新接口。
You will need to add the selected
attribute before passing it to VueJS. 在将其传递给VueJS之前,您需要添加
selected
属性。
BUT ,there is some method you can call to tell vue that new properties been added: 但是 ,有一些方法可以调用告诉vue添加了新属性:
vm.$set('selected', true) //this will make "selected" propertie trackable
vm。$ set('selected',true)//这将使“选定”属性可跟踪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.