1.安装路由
npm i vue-router
注意vue-cli 项目,使用的vue add router
添加vue Router,但是它会覆盖你的App.vue,因此提前备份这个文件,在运行此命令
2.在src中,创建Routers文件夹下创建index.js
3.在src目录下创建 组件
/src/views/Home.vue
/src/views/About.vue
4.在Routers文件夹下创建index.js中导入 VueRouter、组件, 定义路由
import VueRouter from 'vue-router'
import Home from '../components/Home'
import About from '../components/About'
// 定义路由
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
//
- 在routers 路由模块中 创建router实例并导出
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
export default router;
6.在main.js中使用VueRouter挂载到vue实例上
import router from 'vue-router'
new Vue({
render: h => h(App),
router
}).$mount('#app')
7.在 App.vue中,定义路由链接
<template>
<div id="app">
<h3>根组件</h3>
<router-link to="/home">Home页面</router-link>
<router-link to="/about">About页面</router-link>
</div>
</template>
8.App.vue中,定义组件显示位置
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
嵌套路由
// 定义 嵌套路由
const routes = [
{ path: '/home',
component: Home,
children: [
{
path: "news",
component: News
},
{
path: "sports",
component: Sports
},
]},
{ path: '/about', component: About }
]