在 Vue.js 中,使用 vue-router 库定义路由:安装 vue-router 库。在 Vue.js 实例中安装 vue-router。创建一个 Router 实例,指定路由定义(path、component 等)。定义路由,包括路径、组件、名称等选项。

Vue 路由定义
在 Vue.js 中,通过路由系统来管理应用程序中的页面导航和状态管理。要定义路由,需要使用 vue-router 库,它为 Vue 提供了路由功能。
定义路由的过程如下:
-
安装
vue-router库:立即学习“前端免费学习笔记(深入)”;
npm install vue-router
-
在 Vue.js 实例中安装
vue-router:// main.js import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
-
创建一个
Router实例:// router.js import VueRouter from 'vue-router' export default new VueRouter({ routes: [ // 路由定义 ] }) -
定义路由:
// 路由定义示例 { path: '/home', // 路由路径 component: Home // 组件 }
路由定义选项:
- path:指定路由的路径(URL)。
- component:指定要渲染到该路由的 Vue 组件。
- name:给路由指定一个名称,用于在代码中动态导航。
- props:传递给组件的属性对象。
- redirect:当用户访问此路由时,重定向到其他路由。
示例:
// router.js
export default new VueRouter({
routes: [
{
path: '/',
component: Home,
name: 'home'
},
{
path: '/about',
component: About,
name: 'about'
}
]
})在上面的示例中,定义了两个路由:'/' 路由映射到 Home 组件,并命名为 home;'/about' 路由映射到 About 组件,并命名为 about。











