vue3 选中一级菜单二级也选中
时间: 2023-11-14 18:03:07 浏览: 46
在Vue3中,要实现选中一级菜单同时选中二级菜单,可以通过使用v-model指令和计算属性来实现。
首先,使用v-model指令来绑定一级菜单的选中状态,当一级菜单选中时,v-model指令会自动更新绑定的数据。例如:
```html
<template>
<div>
<ul>
<li v-for="item in menuList" :key="item.id" @click="selectFirstLevel(item.id)" :class="{ active: selectedFirstLevel === item.id }">{{ item.name }}</li>
</ul>
<ul>
<li v-for="subItem in selectedSecondLevelList" :key="subItem.id" @click="selectSecondLevel(subItem.id)" :class="{ active: selectedSecondLevel === subItem.id }">{{ subItem.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuList: [
{ id: 1, name: '一级菜单1', children: [{ id: 11, name: '二级菜单1'},{ id: 12, name: '二级菜单2' }] },
{ id: 2, name: '一级菜单2', children: [{ id: 21, name: '二级菜单1'},{ id: 22, name: '二级菜单2' }] }
],
selectedFirstLevel: 1,
selectedSecondLevelList: []
}
},
methods: {
selectFirstLevel(id) {
this.selectedFirstLevel = id;
this.selectedSecondLevelList = this.menuList.find(item => item.id === id).children;
this.selectedSecondLevel = this.selectedSecondLevelList[0].id;
},
selectSecondLevel(id) {
this.selectedSecondLevel = id;
}
},
computed: {
selectedSecondLevel() {
return this.selectedSecondLevelList.find(item => item.id === this.selectedSecondLevel);
}
}
}
</script>
```
这样通过设置v-model指令绑定一级菜单的选中状态,并通过计算属性和方法来处理二级菜单的选中状态,就可以实现选中一级菜单同时选中二级菜单的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)