1.安装vue-router
* λ npm info vue-router versions 查看路由所有版本号
* yarn add vue-router@版本号 安装路由
* npm install vue-router 项目中加入路由(在创建项目时也可以选择安装)
- vue3插件volar来代替vue2的插件vetur,并禁用vetur
2. 初始化vue-router
关键文件:
main.ts
app.vue
components:{xmy,xmy2}
main.ts关键代码:
import xmy from './components/xmy.vue'
import xmy2 from './components/xmy2.vue'
const history = createWebHashHistory() **新建history对象**
const router = createRouter({ **新建router对象**
history:history,
routes:[
{path:'/',component: xmy},
{path:'/xxx',component:xmy2}
]
})
const app = createApp(App)
app.use (router) **//使用router**
app.mount('#app')
app.vue:
<template>
<div>导航栏 | <router-link to="/">1</router-link>
<router-link to="xxx">2</router-link></div>
<hr/>
<router-view/> **添加<router-view></router-view>添加<router-link></router-link>**
</template>
关键步骤:
- 新建history对象
- 新建router对象
- 引入TypeScript
- app.use(router)
- 添加router-view
- 添加router-link