Vue中路由的巢狀
阿新 • • 發佈:2020-09-06
main.js
import Vue from 'vue'; import App from './App.vue'; //引入公共的scss 注意:建立專案的時候必須用scss import './assets/css/basic.scss'; /*路由的巢狀 1.配置路由 { path: '/user', component: User, children:[ { path: 'useradd', component: UserAdd }, { path: 'userlist', component: Userlist } ] } 2.父路由裡面配置子路由顯示的地方 <router-view></router-view>*/ //請求資料 import VueResource from 'vue-resource'; Vue.use(VueResource); import VueRouter from 'vue-router'; Vue.use(VueRouter); //1.建立元件 import Home from './components/Home.vue'; import News from './components/News.vue'; import Content from './components/Content.vue'; import User from './components/User.vue'; import UserAdd from'./components/User/UserAdd.vue'; import Userlist from './components/User/Userlist.vue'; //2.配置路由 注意:名字 const routes = [ { path: '/home', component: Home }, { path: '/news', component: News,name:'news' }, { path: '/user', component: User, children:[ { path: 'useradd', component: UserAdd }, { path:'userlist', component: Userlist } ] }, { path: '/content/:aid', component: Content }, /*動態路由*/ { path: '*', redirect: '/home' } /*預設跳轉路由*/ ] //3.例項化VueRouter 注意:名字 const router = new VueRouter({ mode: 'history', /*hash模式改為history*/ routes // (縮寫)相當於 routes: routes }) //4、掛載路由 new Vue({ el: '#app', router, render: h => h(App) }) //5 <router-view></router-view> 放在 App.vue
app.vue
<template> <div id="app"> <header class="header"> <router-link to="/home">首頁</router-link> <router-link to="/news">新聞</router-link> <router-link to="/user/useradd">使用者</router-link> </header> <hr> <router-view></router-view> </div> </template> <script> export default { data () { return { msg:'你好vue' } } } </script> <style lang="scss"> .header{ height:4.4rem; background:#000; color:#fff; line-height:4.4rem; text-align:center; a{ color:#fff; padding:0 2rem } } </style>
user.vue
<template> <!-- 所有的內容要被根節點包含起來 --> <div id="user"> <div class="user"> <div class="left"> <ul> <li> <router-link to="/user/useradd"> 增加使用者</router-link> </li> <li> <router-link to="/user/userlist"> 使用者列表</router-link> </li> </ul> </div> <div class="right"> <router-view></router-view> </div> </div> </div> </template> <script> export default{ data(){ return { msg:'我是一個user元件' } } } </script> <style lang="scss" scoped> .user{ display:flex; .left{ width:200px; min-height:400px; border-right:1px solid #eee; li{ line-height:2; } } .right{ flex:1; } } </style>