路由基础※
安装※
npm install vue-router
引用※
如皋在一个模块化工程中使用它,必须通过Vue.use()明确的安装路由功能
import VueRouter from 'vue-router'
Vue.use(VueRouter)
如果使用全局的script标签则无须如此
创建路由※
import Component from "./components/Component"
const router = new VueRouter({
routes:[
{
path:"路径/",
name:"名称Component",
component:"组件对象Component"
}
]
})
给出Router显示的位置※
# App.vue
<template>
<router-view />
</template>
将路由注入到实例※
# App.vue
new Vue({
el:'#app',
router,
components:{app},
template:'<app/>'
})
剥离路由※
# src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Component from "@/components/Component"
const router = new VueRouter({
routes:[
{
path:"路径/",
name:"名称", // 跳转使用
component:"组件对象Component"
}
]
})
路由跳转※
<router-link tag="li" to="name"></router-link>
路由嵌套※
# src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Component from "@/components/Component"
const router = new VueRouter({
routes:[
{
path:"/user/:id",
name:"User", // 跳转使用
component:"User"
}
]
})
<template>
<p> {{ this.$route.params.id }} </p>
</template>
路由嵌套※
# src/router/index.js
import Vue from ''vue
import VueRouter from 'vue-router'
import child from '@/components/Child'
Vue.use(VueRouter)
import Child from "@/components/Child"
const router = new VueRouter({
routes:[
{
path:"/user",
name:"User", // 跳转使用
component:"User",
children:[{
path:"child", // 前缀无/
component:child
}]
}
]
})
# 在Child给出Router显示的位置<router-view />
编程式的导航※
# router.push(location.onComplete?,onAbort?)
# router.push(“home”) // 字符串
# router.push({path:'home'}) // 对象
# router.push({name:'user',params:{user:1234}}) // 命名路由
# router.push({path:'register',query:{plan:'private'}}) // 带查询参数 如 /register?plan=private
methods:{
gotoroot(){
this.$router.push("/")
}
}
#router.replace(location.onComplete?,onAbort?) // 不会为后退history添加记录
#router.go(n) // 前进/后退几步 负数为前进
命名路由※
<router-link tag="li" :to="{{name:'user'},params:{id:123}}">User</router-link> // 跳转
{{this.$route.params.id}} // 获取参数
重定向※
# src/router/index.js
import Vue from ''vue
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import NotFound from "@/components/NotFound"
const router = new VueRouter({
routes:[
{
path:"/",
redirect:"/index"
},
{
path:"*",
component:NotFound // 404
},{
path:{"/a",component:A,alias:"/b"} // /b会访问/a,但url还是/b
}
]
})
高亮※
.router-link-active{
color:red;
}
# linkActiveClass:"active" 加在index.js 可使router-link-active变为active
# router-link-exact-active // 包含父级