引入vue-router
可以通过以下方式引入:
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
// 在这里定义你的路由和组件
const routes = [
// ...
];
const router = new VueRouter({
routes,
});
// 将 router 添加到 Vue 实例中
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
vue-router 特色标签及作用
-
<router-link>
:用于生成页面中的链接,使用户可以点击导航到不同的页面。 -
<router-view>
:用于显示当前路由匹配到的组件。
使用vue-router设计路由
在上述的代码中,routes
数组用于定义路由。每个路由对象包含 path
(路径)和 component
(对应的组件)等属性。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
// ...其他路由
];
历史记录在vue-router中的使用
Vue Router 使用 HTML5 历史模式和 hash 模式来管理路由。在创建 VueRouter
实例时,可以通过 mode
属性来指定使用的模式:
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes,
});
路由传参
可以在路由路径中使用动态片段来传递参数:
const routes = [
{ path: '/user/:id', component: UserProfile },
];
在组件中,可以通过 $route.params.id
来获取参数值。
实现嵌套路由
嵌套路由是通过在父路由的组件中使用 <router-view>
来实现的。在路由配置中,可以嵌套定义子路由:
const routes = [
{
path: '/parent',
component: Parent,
children: [
{ path: 'child', component: Child },
],
},
];
命名视图
通过 name
属性为路由视图命名,以支持多个视图的同时显示。
const routes = [
{
path: '/',
components: {
default: Home,
sidebar: Sidebar,
footer: Footer,
},
},
];
重定向
使用 redirect
属性来实现路由重定向:
const routes = [
{ path: '/a', redirect: '/b' },
];
导航守卫分类
导航守卫用于在路由发生变化时执行一些操作。主要分为全局守卫、路由独享守卫、组件内守卫。
- 全局守卫:
beforeEach
、afterEach
、beforeResolve
- 路由独享守卫:在路由配置中使用
beforeEnter
- 组件内守卫:
beforeRouteEnter
、beforeRouteUpdate
、beforeRouteLeave
路由元信息和路由过渡动效
路由元信息是一个对象,可以在路由配置中添加,用于存储一些额外的信息。
const routes = [
{ path: '/example', component: Example, meta: { requiresAuth: true } },
];
路由过渡动效可以通过在组件中使用 <transition>
来实现,或者通过 router-view
上添加 name
属性。
动态路由
通过使用动态路径参数,可以实现动态路由:
const routes = [
{ path: '/user/:id', component: UserProfile },
];
在组件中,通过 $route.params.id
获取动态参数的值。