vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
一、说明
官方提供的用来实现 SPA 的 vue 插件
github:https://github.com/vuejs/vue-router
中文文档:http://router.vuejs.org/zh-cn/
下载:npm install vue-router --save
二、使用步骤
1、定义路由组件:VueRouter():用于创建路由器的构建函数
new VueRouter({
routes:[
{// 一般路由
path:'/about',
component:About
},
{// 自动跳转路由
path:'/',
redirect:'/about'
}
]
})
2、注册路由器
import router from'./router'
new Vue({
router
})
3、使用路由组件标签
(1)、
:用来生成路由链接
(2)、
:用来显示当前路由组件界面
三、基本路由
1、定义路由组件:router/index.js
export default newVueRouter({
routes:[
{
path:'/',
redirect:'/about'
},
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
2、注册路由器:main.js
import Vue from'vue'
import router from'./router'
//创建 vue 配置路由器
newVue({
el:'#app',
router,
render:h=>h(app)
})
3、使用路由标签:App.vue
About
Home
四、嵌套路由
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message
}
]
五、向路由组件传递数据
1、方式1:路由路径携带参数(param或query)
(1)、 路由路径
{{message.title}}
(2)、配置路由
children:[
{
path: '/home/message/detail/:id',
component: MessageDetail
}
]
(3)、 路由组件中读取请求参数 this.$route.params.id
2、方式2:
属性携带数据
(1)、
传递参数。类似props
(2)、路由组件中接收请求参数
export default {
props:{
msg: String
}
}
六、缓存路由组件
1、默认情况下, 被切换的路由组件对象会死亡释放, 再次回来时是重新创建的
2、如果可以缓存路由组件对象, 可以提高用户体验
七、编程式路由导航
1、this.$router.push(path)
:相当于点击路由链接(可以返回到当前路由界面)
2、this.$router.replace(path)
:用新路由替换当前路由(不可以返回到当前路由界面)
3、this.$router.back()
:请求(返回)上一个记录路由
4、this.$router.go(-1)
:请求(返回)上一个记录路由
5、this.$router.go(1)
:请求下一个记录路由