我是Vue.js的新手。
list.vue:
<template>
<div class="m-products-list">
<ul @mouseover="over">
<Item
v-for="(item,idx) in parentList"
location="item.location"
:key="idx"
:meta="item"/>
</ul>
</div>
</template>
<script>
export default {
...
methods: {
over: function (e) {
let dom = e.target;
let tag = dom.tagName.toLowerCase();
if (tag === 'dd') {
console.log(dom.getAttribute('location'))
}
}
}
}
</script>
Item
来自其父组件。而且,当我将鼠标悬停在item.location
上时,我想在over()
中获得item
,但是console.log
总是返回null
。有人有主意吗?
答案 0 :(得分:1)
通过在Item
中设置data-*
attribute,这在技术上是可行的(但下一节可能会有更好的选择)。
// Item.vue
<li :data-location="location" class="item" ... >
new Vue({
el: '#app',
data() {
return {
items: [
{id: 1, location: 'New York'},
{id: 2, location: 'Los Angeles'},
{id: 3, location: 'Chicago'},
]
}
},
components: {
Item: {
props: ['location'],
template: `<li :data-location="location" class="item">{{location}}</li>`,
}
},
methods: {
over(e) {
console.log(e.target.dataset.location)
}
}
})
<script src="https://unpkg.com/vue@2.6.7/dist/vue.min.js"></script>
<div id="app">
<ul @mouseover="over">
<Item v-for="item in items"
:key="item.id"
:location="item.location" />
</ul>
</div>
不需要DOM操作的更好的解决方案是在Vue中使用数据模型并将mouseover
事件侦听器移动到Item
:
将over()
的参数更改为位置名称(以前是事件对象):
methods: {
over(location) {
/* ... */
}
}
将@mouseover
事件侦听器批注从ul
移动到模板中的Item
,并将item.location
作为参数传递:
<ul>
<Item v-for="item in items" @mouseover="over(item.location)" ... />
</ul>
编辑Item
的模板以将其mouseover
事件转发给父对象:
// Item.vue
<li @mouseover="$emit('mouseover', $event)" ... >
new Vue({
el: '#app',
data() {
return {
items: [
{id: 1, location: 'New York'},
{id: 2, location: 'Los Angeles'},
{id: 3, location: 'Chicago'},
]
}
},
components: {
Item: {
props: ['location'],
template: `<li @mouseover="$emit('mouseover', $event)" class="item">{{location}}</li>`,
}
},
methods: {
over(location) {
console.log(location)
}
}
})
<script src="https://unpkg.com/vue@2.6.7/dist/vue.min.js"></script>
<div id="app">
<ul>
<Item v-for="item in items"
:key="item.id"
:location="item.location"
@mouseover="over(item.location)" />
</ul>
</div>