文章目录
- 前言
- 一、安装
- 二、路由对象
- 1.定义
- 2.路由对象属性
- 三、用法
- 1.项目初始化--引入
- 2.主入口文件App.vue
- 3.嵌套路由 (router-link)
- 嵌套路由配置
- 嵌套路由使用
- 4.动态路由匹配
- 使用场景
- 单个路径参数
- 多段路径参数
- 获取当前路由参数
- 5.编程式导航
- 1.router.push()
- 2.router.replace()
- 3.router.go(n)
- 6.命名路由
- 7.命名视图
- 1.概念
- 2.嵌套命名视图
- 8.重定向和别名
- 1.重定向
- 2.命名路由重定向
- 4.回调方法重定向
- 5.别名
前言
提示:本文是跟随vue-router官网逐步展开,希望能更深入了解vue-router基础和使用,相关顺序会打乱,请谅解😊
一、安装
- 戳这里下载 / CDN
- NPM
npm install vue-router
在模块化工程中使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
二、路由对象
1.定义
一个路由对象 (route object) 表示当前激活的路由的状态信息,包含了当前 URL 解析得到的
信息,还有 URL 匹配到的路由记录 (route records)。
注意点:
- 路由是不可变的,每次成功导航后都会产生一个新的对象
- 路由对象出现在多个地方:
- 组件内,即this.$route
- $route观察者内回调
- router.match(location)的返回值
- 导航守卫的参数
router.beforeEach((to, from, next) => {
// `to` 和 `from` 都是路由对象
})
- scrollBehavior方法的参数
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
// `to` 和 `from` 都是路由对象
}
})`
2.路由对象属性
- $route.path:当前路由的路径,总是解析为绝对路径,如
/foo/bar
(string) - $route.params:key/value对象,包含动态片段和全匹配片段,没有则为
{}
- $route.query:key/value对象,表示URl参数,例如:
/foo?user=1
即route.query.user==1
- $route.hash:当前路由的hash值(带#),没有则为空字符串
- $route.fullPath:完成解析后的URl,包含查询参数hash的完整路径
- $route.matched:Array,包含当前路由的所有嵌套的路由记录
- $route.name:当前路由的名称
- $route.redirectedFrom:如果存在重定向,即为重定向来源的路由的名字
//路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
const router = new VueRouter({
routes: [
// 下面的对象就是路由记录
{
path: '/foo',
component: Foo,
children: [
// 这也是个路由记录
{ path: 'bar', component: Bar }
]
}
]
})
当 URL 为 /foo/bar,$route.matched 将会是一个包含从上到下的所有对象 (副本)
ps: hash值如何设置呢?一般在index.js中创建路由时设置
const router = new VueRouter({
mode: 'hash', //设置为hash则路径中会带有#,设置为history则没有
base: process.env.BASE_URL,
routes
})
这里了解到hash是一种url模式,另外一种是history,history模式是需要后台去设置,大家可以去百度帮看看 url hash模式戳这里
三、用法
1.项目初始化–引入
这里说一下,一般项目中都会新建一个router文件夹,下有router.js(包含所有路径配置),然后在main,js中引入
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
// 主界面/首页
{
path: '/',
name: 'Home',
component: import('../views/Home.vue')
},
// 其他
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
path: '*',
redirect: '/404'
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 解决路由点击多次报错,重写路由push
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error => error)
}
export default router
main.js
import router from './router'
new Vue({
router, //挂载
render: h => h(App)
}).$mount('#app')
2.主入口文件App.vue
一般项目都会有主入口也就是上文router.js中的主界面,即项目首页,这个我们直接在App.vue里面放置
<template>
<div id="app">
<router-view/> //所有路由配置的页面会在这里展示,默认展示跟路径即首页路径
</div>
</template>
//组件内可以通过this.$router访问路由器,也可以通过this.$route访问当前路由
如下图:
3.嵌套路由 (router-link)
*上文只提到router-view,但还有个标签router-link,通过router-link点击可以进入路由界面,下面用嵌套路由做相关示例
嵌套路由配置
在router->router.js文件中加入嵌套路由代码
{
path: '/user',
component: () => import('../views/user.vue'),
children: [{
path: 'userOne',
name:'userOne',
component: () => import('../views/userOne.vue')
},
{
path: 'userTwo',
name:'userTwo',
component: () => import('../views/userTwo.vue')
}
]
}
嵌套路由使用
- router-link使用
<template>
<div class="home">
这里是user文件
<router-link to='/user/userOne'>toUserOne</router-link>
<router-link to='/user/userTwo'>toUserTwo</router-link>
</div>
<router-view></router-view>
</template>
- 绑定点击事件js跳转
<template>
<div class="home">
这里是user文件
<div @click='userOne' >去userOne</div>
<div @click='userTwo'>去userTwo</div>
</div>
<router-view></router-view>
</template>
<script>
export default {
name: 'user',
methods:{
userOne(){
this.$router.push('/user/userOne')
},
userTwo() {
this.$router.push('/user/userTwo')
}
}
}
</script>
这里会有个报错就是双击时候回报错,导航重复,解决方案就是在router.js中重写路由push方法,上文有提到
运行结果:
4.动态路由匹配
使用场景
项目中会有一个界面复用多次,比如商城中的商品详情页,我们只需要传不同的id就可以进行不同数据信息的展示
单个路径参数
代码示例
//router -> index.js
{
path: '/about/:id', //此处拼接id
name: 'About',
component: () => import('../views/About.vue')
},
//随意新建一个页面,点击即可访问
<template>
<div id="app">
<div id="nav">
<router-link to="/about/1">About</router-link>
</div>
<router-view/>
</div>
</template>
多段路径参数
index.js
{
path: '/about/:id/other/:otherid',
name: 'About',
component: () => import('../views/About.vue')
}
html
<template>
<div id="app">
<div id="nav">
<router-link to="/about/1/other/2">About</router-link>
</div>
<router-view/>
</div>
</template>
运行结果
获取当前路由参数
this.$route.params
this.$route.query
上述两种的区别:
query是url中含有查询参数 如,www.baodu?id=1
如果是直接以 / 分隔的参数,则可以在params中获取
5.编程式导航
1.router.push()
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
2.router.replace()
和push()很像,区别在于不会向history添加新记录,而是替换掉当前的history记录
3.router.go(n)
前进或者后退几步,类似window.hostory.go(n)
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
6.命名路由
其实就是给路由起一个名字 name
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
<router-link :to="{ name: 'user', params: { userId: 123 }}">User
</router-link>
7.命名视图
1.概念
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
如上所示:name代表a,b,没有name属性则是default显示
2.嵌套命名视图
类似于导航显示不同的视图内容
html:
//home文件
<template>
<div class="hellos">
<div class="hello" >
<ul class='uls'>
<li><router-link to="/list1">list1</router-link></li>
<li><router-link to="/list2">list2</router-link></li>
<li><router-link to="/list3">list3</router-link></li>
</ul>
<div class='main'>
<div class="view" v-if='name=="a"'>
<router-view name="a"></router-view>
</div>
<div class="view" v-if='name=="b"'>
<router-view name="b"></router-view>
</div>
<div class="view" v-else>
<router-view></router-view>
</div>
</div>
</div>
</div>
</template>
index.js
import Home from '../views/Home.vue'
import List1 from '../components/list1.vue'
import List2 from '../components/list2.vue'
import List3 from '../components/list3.vue'
//这里是一组路由配置,以主界面为入口
{
path: '/',
name: 'home',
component: Home,
children: [{
path: '',
components: {
default: List1,
a: List2,
b: List3
}
},
{
path: 'list1',
components: {
default: List1,
a: List2,
b: List3
}
},
{
path: 'list2',
components: {
default: List2,
a: List1,
b: List3
}
},
{
path: 'list3',
components: {
default: List3,
a: List1,
b: List2
}
}
]
}
//default是默认会显示的,a和b即为router-view的name
运行结果:
8.重定向和别名
1.重定向
先理解下为什么使用重定向,即开发中有时候我们设置的路劲不一致,但我们希望跳转到同一个页面,或者说打开同一个组件,就用到了重定向redirect参数
router.js
// 重定向
{
path: '/user',
component: () => import('../views/user.vue')
},
{
path:'/other',
redirect:'/user' //重定向至user页面
}
随便一个页面写一个按钮跳转 ,user也是随便一个已经存在的页面,前提是配置过路由的
<div @click='toUser'> 重定向到user</div>
methods:{
toUser() {
this.$router.push('/other')
}
}
2.命名路由重定向
其实就是用router对象的name标识重定向到那个页面
{
path: '/user',
name:'user', //这里的name必须一致
component: () => import('../views/user.vue')
},
{
path:'/other',
redirect:{name:'user'}
}
4.回调方法重定向
//跳转函数
toUser() {
this.$router.push('/other/2')
}
//router.js配置
{
path:'/other/:id',
redirect:to=>{
console.log(to.params,'跳转事') // 2
if(to.params.id == 2) {
return {path: '/user'}
} else {
// 不进行跳转
}
}
}
我们看到路由后面加了个参数,redirect会返回当前路由信息,可以在回调函数里通过判断 参数进行动态跳转
5.别名
// 重定向
{
path:'/other',
alias: '/b',
component:()=>import( '../views/user.vue'),
},
如上代码所示:即访问
/other
和访问/b
都会跳转到user这个组件
/b
就是/other
的别名
下文请看 搞懂vue-router/嵌套、命名路由/路由重定向…(二)
更多推荐
搞懂vue-router/嵌套、命名路由/路由重定向...(一)
发布评论