vue3+element plus 中el-menu 怎么实现路由跳转

 

 

  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,我们需要安装 `element-plus`,这是 `ElementUI` 的 `Vue3` 版本。 ```bash npm install element-plus --save ``` 然后,在 `main.js` 文件引入并注册 `ElementPlus`。 ```js import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' import App from './App.vue' const app = createApp(App) app.use(ElementPlus) app.mount('#app') ``` 接下来,我们需要将 `el-menu` 组件封装成一个新的组件 `el-cascader-menu`,并在其使用 `el-cascader` 组件来实现级联选择效果。 ```html <template> <el-cascader v-model="selected" :options="options" :props="props" :show-all-levels="false" @change="handleChange" ></el-cascader> </template> <script> import { ref, watch } from 'vue' import { useRoute } from 'vue-router' export default { name: 'ElCascaderMenu', props: { menuList: { type: Array, required: true } }, setup(props) { const route = useRoute() const selected = ref([]) const options = ref(props.menuList) const propsData = { checkStrictly: true, value: 'id', label: 'title', children: 'children' } const props = ref(propsData) watch( () => props.value, () => { options.value = props.menuList } ) const handleChange = (value) => { const path = value.map((id) => { const item = options.value.find((item) => item.id === id) return item.path || item.url }) route.push(path.join('/')) } return { selected, options, props, handleChange } } } </script> ``` 在 `setup` 函数,我们使用 `ref` 创建了 `selected`、`options`、`props` 三个响应式变量,并使用 `watch` 监听 `props.value` 的变化来更新 `options` 的值。 `handleChange` 函数用来处理选择项的变化,并使用 `vue-router` 来实现路由跳转。 最后,我们需要在 `App.vue` 文件引入并使用 `el-cascader-menu` 组件。 ```html <template> <div id="app"> <el-cascader-menu :menuList="menuList" /> </div> </template> <script> import ElCascaderMenu from '@/components/ElCascaderMenu.vue' export default { name: 'App', components: { ElCascaderMenu }, data() { return { menuList: [ { id: '1', title: '导航1', children: [ { id: '1-1', title: '选项1', children: [ { id: '1-1-1', title: '选项1-1', url: '/option-1-1' }, { id: '1-1-2', title: '选项1-2', url: '/option-1-2' } ] }, { id: '1-2', title: '选项2', url: '/option-2' } ] }, { id: '2', title: '导航2', children: [ { id: '2-1', title: '选项1', url: '/option-2-1' }, { id: '2-2', title: '选项2', url: '/option-2-2' } ] } ] } } } </script> ``` 在 `menuList` ,我们使用了 `children` 字段来实现级联选择的效果。当某一层级的选项被选后,其子选项会自动展示在下一层级。 最终效果如下所示: ![el-cascader-menu](https://user-images.githubusercontent.com/26276002/138021340-2b3d6e3d-6c7c-4d19-aa1a-7b2e1d0f05d2.gif)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值