//监听window的 onhashchange事件,根据获取到的最新的hash值,切换要显示的组件的名称
window.onhashchange = function(){
//通过location.hash获取到最新的hash值
}
官网:https://router.vuejs.org/zh/
是Vue.js 官方的路由管理器。
它和Vue.js的核心深度集成,可以非常方便的用于SPA应用程序的开发
Vue Router包含的功能有:
进阶
导航守卫
过渡动效
数据获取
路由懒加载
引入相关的库文件
添加路由链接
登陆
添加路由填充位
定义路由组件
var User = {
template: 'User'
}
配置路由规则并创建路由实例
//创建路由实例对象
var router = new Router({
// routes 是路由规则数组
routes: [
// 每个路由规则都是一个配置对象,至少包含 path和component两个属性:
// path 表示当前路由规则匹配的hash地址
// component表示当前路由对应要展示的组件
{path: '/user', component: User}
{path: 'register', component: register},
]
})
把路由挂载到Vue根实例中
new Vue({
el: '#app',
// 为了能够路由规则生效,必须把路由对象挂载到vue实例对象上
router
});
路由重定向指的是:用户在访问地址A的时候,从而展示特定的组件页面
通过路由规则的redirect属性,指定一个新的路由地址,可以很方便地设置路由的重定向
var router = new VuewRouter({
routes: [
//其中。path表示需要被重定向的原地址,redirect表示将要被重定向的新地址
{path: '/', redirect: '/user'},
{path: '/user', component: User},
]
})
User
const Register = {
template: `
Register 组件
tab1
tab2
`
}
const router = new Router({
routes: [
{
path: '/',
name: 'index',
component: index,
//通过children 属性,为/index 添加子路由
children: [
{path: 'register', component: register},
{path: 'login', component: login},
]
},
})
应用场景:通过动态路由参数的模式进行路由匹配
var router = new VueRouter({
routes: [
//动态路径参数,以冒号开头
{path: '/user/:id', component: User}
]
})
const User = {
//路由组件中通过$route.params 获取路由参数
template: 'User {{ $route.params.id }}'
}
$route与对应路由形成高度耦合,不够灵活,所以可以使用props将组件和路由解耦
const router = new Router({
routes: [
//如果props 被设置为 true, route.params 将会被设置为组件属性
{path: '/user/:id', component: User, props: true }
]
})
const User = {
props: ['id'], // 使用props 接收路由参数
template: ` 用户信息: {{ id }} ` //使用路由参数
}
const router = new VueRoter((
routes: [
//如果props是一个对象,它会被按原样设置为组件属性
{path: '/user/:id', component: User, props: { uname: 'lili', age: 18}}
]
))
const User = {
props: ['uname', 'age'],
template: ` 用户信息: {{ uname + '-----' +age}} `
}