將App.vue中的HelloWorld相關內容註解或刪除掉,然後將element-plus提供的佈局複製過來放在App.vue中
該佈局為左側選單欄,右邊內容區,右上為頂部,典型的管理後台風格
<template> <!-- <img alt="Vue logo" src="./assets/logo.png"> --> <div class="common-layout"> <el-container> <el-aside width="200px"> <Menu></Menu> </el-aside> <el-container> <el-header height="20px">Header</el-header> <el-main> <router-view></router-view> </el-main> </el-container> </el-container> </div> <!-- <div> <p> <router-link to="/home">Go to Home</router-link> <router-link to="/about">Go to about</router-link> <router-view></router-view> </p> </div> <HelloWorld msg="Welcome to Your Vue.js App"/> --> </template> <script> // import HelloWorld from './components/HelloWorld.vue' import Menu from './components/Menu.vue' export default { name: 'App', components: { // HelloWorld Menu } } </script>
上述程式碼中有Menu.vue元件,需要新建,稍後再新增內容
在src目錄新建routes.js文件,將路由列表寫入,方便其它組件使用
const routes = [ { path: "/home", name: 'home', label: '首页', component: () => import('./components/home.vue'), }, { path: "/about", name: 'about', label: '关于', component: () => import('./components/about.vue'), }, ] export default routes
內容沒有什麼變化,就是將router.js 中的routes抽出來,單獨寫一個檔案
router.js引入並使用routes
import { createRouter, createWebHashHistory } from 'vue-router' import routes from './routes' const router = createRouter({ history: createWebHashHistory(), routes: routes, }) export default router
在components目錄中新建Menu.vue頁面,然後將element-plus中選單元件中Side bar 複製過來。
<template> <el-row class="tac"> <el-col :span="24"> <h6 class="mb-2">Default colors</h6> <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"> <el-sub-menu index="1"> <template #title> <el-icon> <location /> </el-icon> <span>Navigator One</span> </template> <router-link v-for="(item, index) in routes" :to="{ name: item.name }" :key="item.name"> <el-menu-item :index="index"> <span v-text="item.label"></span> </el-menu-item> </router-link> </el-sub-menu> <el-menu-item index="2"> <el-icon> <icon-menu /> </el-icon> <span>Navigator Two</span> </el-menu-item> <el-menu-item index="3" disabled> <el-icon> <document /> </el-icon> <span>Navigator Three</span> </el-menu-item> <el-menu-item index="4"> <el-icon> <setting /> </el-icon> <span>Navigator Four</span> </el-menu-item> </el-menu> </el-col> </el-row> </template> <script> import { Document, Menu as IconMenu, Location, Setting, } from '@element-plus/icons-vue' import routes from '../routes' export default { name: 'Menu', components: { Document, IconMenu,Location, Setting }, data() { return { routes: routes, } }, methods: { handleOpen() { console.log("111") }, handleClose() { console.log("222") }, } } </script>
@element-plus/icons-vue 此套件需要安裝(npm install @element-plus/icons-vue)
element-plus官網中的例子都是ts setup語法寫的,這裡我們改成js 響應式語法
列寬改成:span="24"或更大值,列寬太小會發現灰線在字體中間
引入定義的路由列表routes.js,將內容循環到router-link中
運行效果如下
以上是vue3容器佈局和導航路由如何實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!