vue点击列表弹出对应列表数据
时间: 2024-02-21 19:33:09 浏览: 46
可以通过以下步骤实现在Vue中点击列表弹出对应列表数据:
1. 定义一个数据对象,用于存储列表数据和当前选中项的索引:
```
data() {
return {
list: [
{id: 1, name: 'Item 1'},
{id: 2, name: 'Item 2'},
{id: 3, name: 'Item 3'}
],
selectedIndex: -1,
selectedItem: null
}
},
```
2. 在模板中循环渲染列表,并绑定点击事件:
```
<ul>
<li v-for="(item, index) in list" :key="item.id" @click="selectItem(index)">
{{ item.name }}
</li>
</ul>
```
3. 在selectItem方法中更新selectedIndex和selectedItem:
```
methods: {
selectItem(index) {
this.selectedIndex = index;
this.selectedItem = this.list[index];
}
}
```
4. 渲染选中项的详细信息:
```
<div v-if="selectedItem">
<h2>{{ selectedItem.name }}</h2>
<p>Selected index: {{ selectedIndex }}</p>
</div>
```
完整代码如下:
```
<template>
<div>
<ul>
<li v-for="(item, index) in list" :key="item.id" @click="selectItem(index)">
{{ item.name }}
</li>
</ul>
<div v-if="selectedItem">
<h2>{{ selectedItem.name }}</h2>
<p>Selected index: {{ selectedIndex }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{id: 1, name: 'Item 1'},
{id: 2, name: 'Item 2'},
{id: 3, name: 'Item 3'}
],
selectedIndex: -1,
selectedItem: null
}
},
methods: {
selectItem(index) {
this.selectedIndex = index;
this.selectedItem = this.list[index];
}
}
}
</script>
```
阅读全文