路由有什么用?
在我们修改地址栏路径时,切换显示匹配的组件
VueRouter的使用(5 + 2)
5个基础步骤(固定)
1.下载:下载 VueRouter模块到当前工程,版本3.6.5
yarn add vue-router@3.6.5
npm i vue-router@3.6.5
2.引入
import VueRouter from 'vue-router'
3.安装注册
Vue.use(VueRouter)
4.创建路由对象
const router =new VueRouter()
5.注入,将路由对象注入到new Vue实例中,建立关联
new Vue({
render:h => h(App).
router
}).$mount('#app')
2 个核心步骤
1.创建需要的组件(views目录),配置路由规则
import FirstNav from './views/FirstNav.vue'
import SecondNav from './views/SecondNav.vue'
import ThreeNav from './views/ThreeNav.vue'
const router = new VueRouter({
routes: [{
path: "/FirstNav", component: FirstNav,
},
{
path: "/SecondNav", component: SecondNav,
},
{
path: "/ThreeNav", component: ThreeNav
}
]
})
2.配置导航,配置路由出口(路径匹配的组件显示的位置)
<template>
<div id="app">
<a href="#/FirstNav">1</a>
<a href="#/SecondNav">2</a>
<a href="#/ThreeNav">3</a>
<router-view></router-view>
</div>
</template>