我在 li
元素上使用 v-for
指令从数组中生成一组图像。将鼠标悬停在图像上时,我想将鼠标悬停的特定图像的 id
属性更改为 'drag'
,并且我希望该图像成为唯一具有 id
为 'drag'
的元素。
我尝试使用内联语句绑定(bind)到 :id
,就像 :class
那样,但它不起作用,只是将 id 替换为 >[对象对象]
。
这里我绑定(bind)到 :class
并且它的行为正确:
var app = new Vue({
el: '#app',
data: {
list: [{
Name:'Object 1', link:'obj1.jpg'
}, {
Name:'Object 2', link:'obj2.jpg'
}, {
Name:'Object 3', link:'obj3.jpg'
}],
dragIndex: "",
},
methods: {
drag(item,index) {
console.log("Dragging " + item)
},
startDragID(index) {
this.dragIndex = index
console.log("Element Prepped For Drag: " + index)
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<ul>
<li
v-for="(items,index) in list"
draggable="true"
@mouseenter="startDragID(index)"
@dragstart="drag(items.link,index)"
:class="{'drag' : dragIndex == index , 'not-drag' : dragIndex != index}"
>{{items.Name}}</li>
</ul>
</div>
最佳答案
Vue 不支持使用内联 object syntax 绑定(bind)到 id
属性就像它的 class
和 style
属性一样。
您可以创建一个方法来根据给定的索引
计算适当的id值:
methods: {
getID(index) {
return (index == this.dragIndex) ? 'drag' : false;
}
}
并将该结果绑定(bind)到 id
属性:
<li v-for="(items, index) in list" :id="getID(index)">
或者,由于确定 id 的方法足够简单,您可以添加内联逻辑:
<li v-for="(items, index) in list" :id="(index == dragIndex) ? 'drag' : false">
关于javascript - VueJS 2 : Bind v-for index to id attribute on mouseover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43809385/