Vue Router 是 Vue.js 官方的路由管理器,它允许你在单页面应用中通过不同的 URL 显示不同的组件。Vue Router 与 Vue.js 核心深度集成,提供了声明式的路由定义、嵌套路由、动态路由、导航守卫等功能,帮助开发者构建复杂的单页面应用。
在 Vue 2 项目中,可以通过 npm 或 yarn 安装 Vue Router:注意,vue2要安装3点几的版本
npm install [email protected]
# 或者
yarn add [email protected]
在项目中创建一个 router.js
文件,用于配置路由:
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../components/Home.vue';
import About from '../components/About.vue';
// 使用 Vue Router
Vue.use(VueRouter);
// 定义路由规则
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
];
// 创建路由实例
const router = new VueRouter({
mode: 'history', // 使用 HTML5 历史模式
routes
});
export default router;
在 main.js
中引入路由实例,并将其挂载到 Vue 实例上:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
new Vue({
router,
render: h => h(App)
}).$mount('#app');
和
在 Vue 模板中,使用
创建导航链接,使用
显示当前路由对应的组件。
Vue Router 示例
动态路由允许你在 URL 中传递参数。例如:
const routes = [
{
path: '/user/:id',
name: 'User',
component: User
}
];
在组件中,可以通过 $route.params
获取参数:
用户详情
用户 ID:{{ $route.params.id }}
嵌套路由允许你在某个组件内部定义子路由。例如:
const routes = [
{
path: '/parent',
component: Parent,
children: [
{
path: 'child',
component: Child
}
]
}
];
在模板中,使用
显示子路由:
父组件
Vue Router 提供了导航守卫(Navigation Guards),可以在路由跳转前后执行一些逻辑。例如:
router.beforeEach((to, from, next) => {
if (to.path === '/login') {
next();
} else {
if (!isAuthenticated) {
next('/login');
} else {
next();
}
}
});
为路由命名后,可以通过名称进行跳转:
const routes = [
{
path: '/about',
name: 'About',
component: About
}
];
在模板中使用
:
关于
除了
,还可以通过编程方式导航:
this.$router.push({ name: 'About' });
为了优化应用性能,可以使用路由懒加载:
const routes = [
{
path: '/about',
name: 'About',
component: () => import('../components/About.vue')
}
];