路由安装
终端下载路由插件 npm install vue-router --save-dev
配置
在main.js中引入插件
1 //Router 为自定义名 vue-router 为插件的名字 2 3 import Vue from 'vue' 4 5 import Router from 'vue-router'
注册使用
//注册使用 vue-router Vue.use(Router)
配置路由
1 const router = new Router({ 2 routes : [ 3 {path : "/" ,name : "home" component: Home}, 4 {path : "/helloworld" , name : "helloworld",component: HelloWorld} 5 ], 6 mode : "history" //去掉路由地址后面的# 7 }) 8 9 //可以将routes单独抽离出来 10 11 const routes = [ 12 { 13 path : "/" , //设置路由路径 14 name : "home", 15 component: Home // home在main.js里面注册的组件名,将要跳转到的组件 16 }, 17 18 {path : "/helloworld" , name : "helloworld",component: HelloWorld}, 19 20 {path : "*" , redirect: '/'} //当点击不存在路径时 默认 跳转到路径 '/' 21 ] 22 23 const router = new Router({ 24 routes,
25 linkActiveClass: 'class' //设置路由比标签选中颜色 26 mode : "history" 27 })
需要在main.js中 vue实例中引入router
1 new Vue({ 2 router, 3 el: '#app', 4 components: { App }, 5 template: '<App/>' 6 })
二级路由的设置
1 //二级路由在当前路由下添加 children数组 2 3 const routes = [ 4 { 5 path : "/about" , //设置路由路径 6 name:'about', 7 component: About, 8 redirect: '/about1', //设置当前页面默认显示的子路由 9 children:[ //二级路由 10 {path : "/about1" ,name:'about1', component: About1}, 11 {path : "/about2" ,name:'about2', component: About2}, 12 {path : "/about3" ,name:'about3', component: About3}, 13 {path : "/about3" ,name:'about3', component: About3}, 14 ] 15 }, 16 ] 17 18 const router = new Router({ 19 routes, 20 mode : "history" 21 })
跳转的几种写法
标签<router-link to=""></router-link>
一、
1 <!-- to属性里面填入路径(在main.js中设置的路径) -->
2 <!-- tag属性可以设置 标签的展示 tag="div"标签是以div形式的展示 -->
3 4 <router-link tag="div" to="/home">首页</router-link>
二、
<!-- 通过 注册路由时设置的 name 属性 --> <router-link :to="{name : 'home'}">首页</router-link> 通过name属性 {path : "/home" ,name:'home', component: Home},
三、
<!-- 可以动态设置路径 --> <router-link :to="home">新闻</router-link>
<!-- 可以通过data动态设置路径 --> data(){ name : '/home' }
通过name属性实现<router-link></router-link>的复用
<router-view name="home1"></router-view> <router-view name="home2"></router-view> <router-view name="home3"></router-view>
const routes = [ { path : "/" , name:'home', components: { //components 这里有 s default : Home, // 当前的home页面 //为复用的 路由设置 属性名 'home1' : Home1, 'home2' : Home2, 'home3' : Home3, } }, ]