1. Vue Router 简介Vue Router 是 Vue.js 的官方路由管理器,它允许开发者构建单页面应用(SPA)。通过 Vue Router,可以实现页面的无刷新切换,提升用户体验和应用...
Vue Router 是 Vue.js 的官方路由管理器,它允许开发者构建单页面应用(SPA)。通过 Vue Router,可以实现页面的无刷新切换,提升用户体验和应用性能。
首先,确保你已经有一个 Vue.js 项目环境。如果没有,可以使用 Vue CLI 创建一个新项目:
vue create my-project
cd my-project然后,安装 Vue Router:
npm install vue-router在项目的入口文件 main.js 中引入并创建一个路由器实例:
import { createApp } from 'vue';
import App from './App.vue';
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About }
];
const router = createRouter({ history: createWebHistory(), routes
});
createApp(App).use(router).mount('#app');路由守卫是 Vue Router 提供的一种功能,用于在路由导航过程中执行代码。它可以用于权限验证、页面访问日志记录等。
router.beforeEach((to, from, next) => { // 在此执行全局前置守卫 next();
});const routes = [ { path: '/about', name: 'About', component: About, beforeEnter: (to, from, next) => { // 在此执行路由独享守卫 next(); } }
];export default { name: 'About', beforeRouteEnter(to, from, next) { // 在此执行组件内守卫 next(); }, beforeRouteUpdate(to, from, next) { // 在此执行组件内守卫 next(); }, beforeRouteLeave(to, from, next) { // 在此执行组件内守卫 next(); }
};路由懒加载可以按需加载组件,优化应用性能。
const routes = [ { path: '/about', name: 'About', component: () => import('./views/About.vue') }
];const routes = [ { path: '/about', name: 'About', component: () => ({ template: '<div>About</div>' }) }
];嵌套路由允许在子路由中定义嵌套的路径和组件。
const routes = [ { path: '/user', component: User, children: [ { path: 'profile', component: UserProfile }, { path: 'posts', component: UserPosts } ] }
];<router-link to="/user/profile">用户资料</router-link>
<router-link to="/user/posts">用户文章</router-link>动态路由匹配允许根据 URL 中的参数动态渲染组件。
const routes = [ { path: '/user/:id', component: User }
];<router-link :to="{ name: 'user', params: { id: 123 }}">用户123</router-link>编程式的路由导航允许通过 JavaScript 代码进行页面跳转。
router.push 方法router.push('/about');router.replace 方法router.replace('/about');router.go 方法router.go(-1); // 返回上一个路由通过以上技巧,你可以轻松实现单页面应用的导航,提升用户体验和应用性能。