Vue实现遍历并交互
Vue实现遍历并交互
在Vue中,可以使用v-for指令遍历数组或对象,并结合事件绑定实现交互功能。以下是一个完整的实现方法:
遍历数组并绑定点击事件
<template>
<div>
<ul>
<li
v-for="(item, index) in items"
:key="index"
@click="handleClick(item)"
>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ name: 'Item 1', id: 1 },
{ name: 'Item 2', id: 2 },
{ name: 'Item 3', id: 3 }
]
}
},
methods: {
handleClick(item) {
console.log('Clicked:', item)
}
}
}
</script>
遍历对象并显示/隐藏内容
<template>
<div>
<div
v-for="(value, key) in userInfo"
:key="key"
@mouseover="showTooltip(key)"
@mouseout="hideTooltip"
>
{{ key }}: {{ value }}
<div v-if="activeTooltip === key" class="tooltip">
Additional info about {{ key }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
userInfo: {
name: 'John',
age: 30,
email: 'john@example.com'
},
activeTooltip: null
}
},
methods: {
showTooltip(key) {
this.activeTooltip = key
},
hideTooltip() {
this.activeTooltip = null
}
}
}
</script>
动态修改遍历的数据
<template>
<div>
<div v-for="(task, index) in tasks" :key="index">
<input
type="checkbox"
v-model="task.completed"
@change="updateTask(index)"
>
<span :class="{ 'completed': task.completed }">
{{ task.text }}
</span>
<button @click="removeTask(index)">Remove</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tasks: [
{ text: 'Learn Vue', completed: false },
{ text: 'Build app', completed: false },
{ text: 'Deploy', completed: false }
]
}
},
methods: {
updateTask(index) {
console.log('Task updated:', this.tasks[index])
},
removeTask(index) {
this.tasks.splice(index, 1)
}
}
}
</script>
使用计算属性实现过滤遍历
<template>
<div>
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="product in filteredProducts" :key="product.id">
{{ product.name }} - ${{ product.price }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
products: [
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Phone', price: 699 },
{ id: 3, name: 'Tablet', price: 399 }
]
}
},
computed: {
filteredProducts() {
return this.products.filter(product => {
return product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
})
}
}
}
</script>
这些示例展示了Vue中遍历数据的多种方式以及如何实现交互功能,包括点击事件、鼠标事件、动态修改数据和过滤显示内容。







