javascript - VueJS 2 : Bind v-for index to id attribute on mouseover

标签 javascript vue.js mouseover vuejs2

我在 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 属性就像它的 classstyle 属性一样。

您可以创建一个方法来根据给定的索引计算适当的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/

相关文章:

javascript - 如何使用 jQuery 阻止鼠标离开太快而缩短背景图像转换

jquery - 选择另一个 div 时删除预加载的类

jquery - 想要在 mouseenter 上发生一次,但发生两次

javascript - 为什么 Node.js 函数不返回 JSDom serializeDocument 结果?

javascript - Vue.js <transition-group> 仅在最后一个元素上应用动画

javascript - $.getJSON 在 IE9 及以下版本返回 undefined 成功回调

javascript - 将库导入到 vue.js 的单个文件组件中

vue.js - 如何使用 Nuxt 保护 API key 并进行验证

javascript - qooxdoo中如何设置窗口高度最大化?

javascript - 使用 jQuery 加载外部 js 文件