0、理解
1、 VueRouter(): 用于创建路由器的构建函数
new VueRouter({
// 多个配置项
})
2、路由配置
routes: [
{ //一般路由
path:'/about',
compontent:About
},
{ //自动化跳转路由
path: '/',
redirect: '/about'
}
]
3、注册路由器
import router from './router'
new Vue ({
router
})
4、使用路由组件标签
- <router-link>: 用来生成路由链接
<router-link to="/xxx">Go to xxx<router-link>
- <router-view>: 用来显示当前路由组件界面
<router-view></router-view>
1、vue-router
是用来实现SPA的vue插件
2、vue-router的基本使用
1、创建路由:router/index.js
new VueRouter({
mode: 'hash/history'
routes: [
{ //一般路由
path:'/about',
compontent:About
},
{ //自动化跳转路由
path: '/',
redirect: '/about'
}
]
})
2、注册路由器:main.js
import router from './router'
new Vue({
router
})
3、使用路由组件标签
- <router-link>: 用来生成路由链接
<router-link to="/xxx">Go to xxx<router-link> //可以不使用
- <router-view>: 用来显示当前路由组件界面
<router-view></router-view> //必须使用
4、2个对象
$router: 代表路由器对象,包含一些实现路由跳转/导航的方法:push()/replace()/back()
$route: 代表当前路由对象,包含一些路由相关的属性: path/params/query/meta
path:请求的path
3、编写路由的3步
- 定义路由组件
- 映射路由
- 使用
显示当前路由组件
4、嵌套路由
children: [
{
path: '/home/news/:id/:title',
component: news
},
{
path: 'message',
component: message
}
]
兄弟路由和嵌套路由的关系区别在哪里?
看布局关系
5、向路由组件传递数据
params/query: < router-link to="/home/news/123/abc?zzz=123"
将请求参数映射成props:props=true | props: route => ({id: route.params.id})
变相props: <router-view msg='abc'>
6、动态路由与别名路由
注册路由:
{
name: 'news'
path: '/home/news/:id/:title',
component: News
}
跳转:
<router-link to="{name: 'news', params:{id:1, title: 'abc'}}">
7、缓存路由组件
理由组件对象默认的生命周期:被切换时就会死亡,切换回来时重新创建
<keep-alive exclude="A,B">
<router-view></router-view>
</keep-alive>
8、路由的编程式导航
this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
this.$router.repleace(path):用新路由替换当前路由(不可以返回到当前路由界面)
this.$router.back(): 请求(返回)上一个记录路由
9、路由的2种模式比较,解决history模式404问题
deServer: historyApiFallback: true, //任意的404响应都被替代为index.html
output: publicPath: '/', // 引入打包的文件时路径以/开头