Vue-router(Vue的核心插件)
用来提供路由功能。 通过路由的改变乐意动态加载组件,达到开发单页面程序的目的
(1)基本应用:在vue中进行路由祖册,在模板中通过router-view来接收路由组件
1.提供组件给路由使用
2.注册组件
3.定义路由对象数组
let routes = [
// 一个路由对象
{
// 路由路径
path: "/a",
// 对应的组件
component: myA,
},
{
path: "/b",
component: myB,
},
];
4.创建路由器对象
new router= newVueRouter({
routes:routes
})
5.注册路由对象
new Vue({
router:router
})
6.使用路由
<router-link to="/a">文字</router-link>
<router-view></router-view>
样例代码
<body>
<div id="app">
<!-- 路由和组件是对应的关系 -->
<!-- 4.使用路由 -->
<!-- to路由去的path路径 -->
<div>
<!-- 导航 -->
<router-link to="/a">去A组件</router-link>
<router-link to="/b">去B组件</router-link>
<!-- href="#/路由路径" -->
<a href="#/a">a标签路由去A</a>
</div>
<!-- 内容区 路由组件显示的位置 -->
<div>
<!-- 放路由产生的组件 -->
<router-view></router-view>
</div>
</div>
<script>
//(1) 声名组件
// 提供组件给路由使用
let myA = {
template: `
<div>A组件</div>
`,
};
let myB = {
template: `
<div>B组件</div>
`,
};
// route路由对象 router路由器对象 routes路由对象数组
// 1.定义路由对象数组
let routes = [
// 一个路由对象
{
// 路由路径
path: "/a",
// 对应的组件
component: myA,
},
{
path: "/b",
component: myB,
},
];
// 2.创建路由器对象
let router = new VueRouter({
// routes属性给1个路由对象数组
routes: routes,
});
new Vue({
el: "#app",
// 3.注册路由器对象
router: router,
// (2)局部注册组件
components: {
"my-a": myA,
"my-b": myB,
},
data: {},
methods: {},
});
</script>
</body>
(2)命名路由(name属性)
在配置路由的时候,为路由指定name属性,相当于为该路由进行命名,方便后期路由的跳转
let router = new VueRouter({
routes: [ {
path: '/user/:userId', name: 'user', component: User
} ]
})
(3)重定向
重定向的意思是,当用户访问 /a时,URL 将会被替换成 /b,然后匹配路由为 /b
1.redirect:'/b', // 重新定向到b路由
2.redirect:{name:'bRoute'} // 使用路由名字进行路由跳转(重定向)
(4)别名
/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就 像用户访问 /a 一样 当访问/a或者/b的时候实际上都打开的是A组件
aloas:'/b',
样例代码
let routes = [
{
path: "/",
component: myA,
// 路由重定向
// 重新定向到a路由
// redirect: "/a",
redirect: { name: "aRoute" },
},
{
path: "/a",
component: myA,
// 路由名称
name: "aRoute",
// 重命名
alias: "/aa",
},
{
path: "/b",
component: myB,
// 路由名称
name: "bRoute",
},
];
(5) 路由对象
{
path:'/a', //(必备)
name:'aRoute', //路由名字
component:myA, //对应的组件 (必备)
alias:'/aa', //重命名
redirect:'/b', //重定向
//redirect:{name:'bRoute'}, //重定向
}
(6)路由守卫
1.全局守卫
全局前置守卫
router.beforeEach((to,from,next)=>{})
全局后置守卫
router.afterEach((to,from)=>{})
2.路由独享守卫
{
path:'',
beforeEnter(to,from,next){}
}
3.组件内守卫
beforeRouteEnter(to, from, next) {
// this-->window
console.log(this, "beforeRouteEnter");
next();
},
beforeRouteUpdate(to, from, next) {
// this--->组件实例
console.log(this, "beforeRouteUpdate");
// next();
},
beforeRouteLeave(to, from, next) {
// this--->组件实例
console.log(this, "beforeRouteLeave");
next();
},