1.路由
注意:项目在初始化的时候不要集成vue-router
2.安装
cnpm install vue-router --save
3.如果在一个模块化工程中使用它,建议专门写一个js文件承载路由文件:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
4.创建路由
const router = new VueRouter({
routes:[
{
path:"/",
name:"HelloWorld",
component:HelloWorld
}
]
})
5.给出路由显示的位置,写在APP.vue中
<router-view />
6.将路由对象注入Vue实例中,写在mian.js中的new Vue
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
技巧:@/components/HelloWorld,@相当于根目录
7.路由跳转router-link
属性:tag
<router-link tag="li" to="/learn">Learn</router-link> //tag表示可以按照li标签的属性去渲染
8.动态路由(参数传递)
/:id 模式
/user/evan 匹配路径
{{ this.$route.params.id }} 页面显示
9.路由嵌套
1.引入子文件
2.路由文件
children:[
{
path:"base",
component:Base
},
{
path:"http",
component:Http
}
]
3.显示:<router-view />
4.跳转
<ul>
<router-link to="/learn/base">基础</router-link>
<router-link to="/learn/http">网络</router-link>
</ul>
10.编程式的导航
router.push
router.replace:跟 router.push 很像,但它不会向 history 添加新记录,而是替换掉当前的 history 记录。
router.go:在 history 记录中向前或者后退多少步
11.命名路由(参数传递)
<router-link tag="li" :to="{name:'HelloWorld', params: { id: helloparams }}">Hello</router-link>
<router-link tag="li" :to="{name:'LearnVue'}">Learn</router-link>
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
this.$router.push({ name: 'HelloWorld', params: { id: this.clickParams }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
12.路由杂项
1.重定向:第一次进入时指定加载的页面
{
path:"/",
// 重定向
redirect:"/learn"
}
2.报错:404
{
path:"*",
component:NotFound
},
3.别名:当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样
{ path: '/a', component: A, alias: '/b' }
4.history模式:URL就像正常的ur,l没有 #
mode:"history"
13.路由高亮
linkActiveClass:"active",
linkExactActiveClass:"currentActive",
router-link-exact-active //精准匹配:只有子级,不传给父级
router-link-active