天天看點

vue學習 35路由精講之複用router-view

分離路由配置檔案

routes.js

import Home from './components/Home'
import Menu from './components/Menu'
import Admin from './components/Admin'
import About from './components/about/About'
import Login from './components/Login'
import Register from './components/Register'

// 二級路由
import Contact from './components/about/Contact'
import Delivery from './components/about/Delivery'
import History from './components/about/History'
import OrderingGuide from './components/about/OrderingGuide'

// 三級路由
import Phone from './components/about/contact/Phone'
import PersonName from './components/about/contact/PersonName'

export const routes = [{
		path: '/',
		name: 'homeLink', //路由的名字
		components: {
			default: Home,
			'orderingGuide': OrderingGuide,
			'delivery': Delivery,
			'history': History
		}
	},
	{
		path: '/menu',
		name: 'menuLink',
		component: Menu
	},
	{
		path: '/admin',
		name: 'adminLink',
		component: Admin
		// beforeEnter: (to, from, next) => {
		// 	alert("非登陸狀态,不能通路此頁面");
		// 	next(false);
		// }
	},
	{
		path: '/about',
		name: 'aboutLink',
		component: About,
		redirect: '/about/contact',
		children: [{
				path: '/about/contact',
				name: "contactLink",
				component: Contact,
				redirect: '/personname',
				children: [{
						path: '/phone',
						name: "phoneNumber",
						component: Phone
					},
					{
						path: '/personname',
						name: "personName",
						component: PersonName
					}
				]
			},
			{
				path: '/history',
				name: "historyLink",
				component: History
			},
			{
				path: '/delivery',
				name: "deliveryLink",
				component: Delivery
			},
			{
				path: '/orderingGuide',
				name: "orderingGuideLink",
				component: OrderingGuide
			},
		]
	},
	{
		path: '/login',
		name: 'loginLink',
		component: Login
	},
	{
		path: '/register',
		name: 'registerLink',
		component: Register
	},
	{
		path: '*', //不是上面所有的路由,則跳轉到指定路由
		name: 'homeLink',
		redirect: '/'
	}
]
           

在main.js中引入routes.js,注意引入的寫法,routes外包有大括号{}

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import {routes} from './routes.js'
           

App.vue根元件,首頁Home路由複用router-view,根據router-view标簽的name屬性值與home路由中的components對象的屬性值對應關系

<br>
		<div class="container">
			<div class="row">
				<div class="col-sm-12 col-md-4">
					<router-view name="orderingGuide"></router-view>
				</div>
				<div class="col-sm-12 col-md-4">
					<router-view name="history"></router-view>
				</div>
				<div class="col-sm-12 col-md-4">
					<router-view name="delivery"></router-view>
				</div>
			</div>
		</div>