Vue 路由
1、引入路由模块,配置路由并实例化
// 引入路由文件 import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' 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' // 定义路由 Vue.use(VueRouter) // 配置路径 const routes = [ {path:'/',name:'homeLink',component:Home}, {path:'/menu',name:'menuLink',component:Menu}, {path:'/admin',name:'adminLink',component:Admin}, {path:'/about',name:'aboutLink',component:About}, {path:'/login',name:'loginLink',component:Login}, {path:'/register',name:'registerLink',component:Register}, {path:'*',redirect:'/'} ] // 实例化 const router = new VueRouter({ routes, mode: 'history' }) new Vue({ el: '#app', router, render: h => h(App) })
2、跳转页面的几种方式
1 <ul class="navbar-nav"> 2 // router-link默认是 a 标签 加tag可指定任意标签 3 //(1) to='路径' 4 <li><router-link tag='div' to="/" >主页</router-link></li> 5 // (2):to='变量' 6 <li><router-link :to="homeLink">主页</router-link></li> 7 //(3):to='{name:''}' 8 <li><router-link :to='{name:"homeLink"}' >主页</router-link></li> 9 </ul> 10 11 <script> 12 // 针对跳转方式(2) 13 export default({ 14 data() { 15 return { 16 homeLink:'/' 17 } 18 } 19 }) 20 </script> 21 22 跳转方式(3)在main.js 配置路径里面 加 name 属性;
3、二级路由
// 引入模块 // 二级路由 import Contact from './components/about/Contact' import History from './components/about/History' import Guide from './components/about/Guide' import Delivery from './components/about/Delivery' const routes = [ {path:'/about',name:'aboutLink',redirect:'/about/contact',component:About,children:[ {path:'/about/contact',name:'contactLink',redirect:'/phone',component:Contact,children:[ {path:'/phone',name:'phoneNumber',component:Phone}, {path:'/person',name:'personName',component:Person} ]}, {path:'/history',name:'historyLink',component:History}, {path:'/guide',name:'guideLink',component:Guide}, {path:'/delivery',name:'deliveryLink',component:Delivery} ]}, {path:'*',redirect:'/'} ]
4、点击路由跳转页面
<template> <div> <h1>Home</h1> <button v-on:click="goToMenu" class="btn btn-success">let us go!</button> </div> </template> <script> export default{ methods: { goToMenu() { // 跳转到上一次浏览的页面 // this.$router.go(-1) // 指定跳转的地址 // this.$router.replace('/menu') // 指定跳转路由的名字下 // this.$router.replace({name:'menuLink'}) // 通过push进行跳转 // this.$router.push('/menu') this.$router.push({name:'menuLink'}) } } } </script>