Vue实现遍历并交互
Vue 中实现遍历与交互的方法
使用 v-for 遍历数组/对象
通过 v-for 指令可以循环渲染列表数据,结合 :key 确保渲染性能:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }}
<button @click="handleClick(index)">交互</button>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item A' },
{ id: 2, name: 'Item B' }
]
}
},
methods: {
handleClick(index) {
console.log('Clicked item index:', index);
}
}
}
</script>
动态修改遍历数据
通过方法直接修改响应式数据,触发视图更新:
methods: {
updateItem(index) {
this.items[index].name = 'Updated';
}
}
使用计算属性过滤数据
通过计算属性实现动态过滤或排序:
computed: {
filteredItems() {
return this.items.filter(item => item.active);
}
}
事件传递与参数绑定
在子组件中触发父组件事件,实现跨组件交互:
<!-- 父组件 -->
<ChildComponent
v-for="item in items"
:item="item"
@custom-event="handleEvent"
/>
<!-- 子组件 -->
<button @click="$emit('custom-event', item.id)">触发事件</button>
使用 Vuex 管理状态
对于复杂交互逻辑,可通过 Vuex 集中管理状态:
// store.js
export default new Vuex.Store({
state: {
items: []
},
mutations: {
updateItem(state, payload) {
state.items[payload.index] = payload.item;
}
}
});
// 组件中调用
this.$store.commit('updateItem', { index, item });
注意事项
- 始终为
v-for提供唯一的:key,通常使用id而非index - 避免直接修改
props中的数据,使用事件或 Vuex 触发变更 - 复杂交互场景建议拆分组件,保持单一职责原则







