这篇文章主要介绍“Vue如何实现嵌套菜单组件”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Vue如何实现嵌套菜单组件”文章能帮助大家解决问题。
本文旨在使用Vue.js完成一个嵌套的菜单组件,使用mock.js对数据进行模拟,并且最小化复现功能
安装mock
cnpm i mockjs
//引入mockjsimport Mock from 'mockjs'//使用mockjs模拟数据Mock.mock('/menuData', 'get', { "ret": 0, "data": [{ "id": 1, "name": "第一层", "children": [{ "name": "第二层" }, { "name": "第二层" }, { "name": "第二层" } ] }, { "id": 2, "name": "第一层", "children": [{ "name": "第二层" }, { "id": 3, "name": "第二层", "children": [{ "name": "第三层" }, { "name": "第三层" }, { "name": "第三层" } ] }, { "id": 4, "name": "第二层", "children": [{ "name": "第三层" }, { "name": "第三层" }, { "id": 5, "name": "第三层", "children": [{ "name": "第四层" }, { "name": "第四层" }, { "id": 6, "name": "第四层", "children": [{ "name": "第五层" }, { "name": "第五层" }, { "name": "第五层" } ] } ] } ] } ] } ]});
菜单组件
<!-- * @Author: byron * @Date: 2022-02-24 09:01:27 * @LastEditTime: 2022-02-24 10:50:38--><template> <div> <ul class="menu" v-for="item in data" :key="item.id"> <li class="subMenu" @click="showhd(item)" :class="[item.children ? 'color' : '']" > <span> {{ item.name }} {{ item.id }}</span> </li> <div class="child" v-if="item.id == currentId && openFlag"> <xxxx v-if="item.children" :data="item.children"></xxxx> </div> </ul> </div></template><script>export default { name: 'xxxx', components: {}, props: ['data'], data() { return { currentId: undefined, openFlag: false, } }, methods: { showhd(a) { console.log(this.openFlag) this.openFlag = !this.openFlag this.currentId = a.id console.log(this.currentId) console.log(this.openFlag) }, },}</script><style scoped>li { text-decoration: none; }.ul { overflow: hidden;}.head { display: none;}.show { display: block;}.color { color: brown;}</style>
使用菜单组件
<template> <div id="app"> <h2>嵌套组件的实现</h2> <HelloWorld :data="menu" /> </div></template><script>import HelloWorld from './components/HelloWorld.vue'import axios from 'axios'export default { name: 'App', components: { HelloWorld, }, data() { return { menu: [], } }, async created() { const { data: r } = await axios.get('/menuData') this.menu = r.data console.log(this.menu) },}</script><style>#app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>
关于“Vue如何实现嵌套菜单组件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网行业资讯频道,小编每天都会为大家更新不同的知识点。