添加包依赖
javascript
"dependencies": {
"vue": "^2.7.7",
"vue-router": "^3.5.4"
},
Vue2对应VueRouter3
Vue3对应VueRouter4
在src/router/index.js中配置路由
javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: import.meta.env.BASE_URL,
routes: [
{
},
]
})
export default router
在main.js中引入router
javascript
import Vue from 'vue'
import App from './App.vue'
import router from './router'
new Vue({
router,
render: (h) => h(App)
}).$mount('#app')
我们做一个简单的案例
点击首页、关于,调到对应的组件
目录结构如下
App.vue
html
<script setup>
</script>
<template>
<div class="app-container">
<h1>App根组件</h1>
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<hr>
<router-view></router-view>
</div>
</template>
<style scoped>
.app-container {
text-align: center;
font-size: 16px;
}
.app-container a {
padding: 10px;
color: #000;
}
.app-container a.routerr-link-active {
color: #fff;
background-color: #000;
}
</style>
HomeView.vue
html
<script>
export default {
name: "HomeView"
}
</script>
<template>
<div class="home-container">
<h3>Home组件</h3>
</div>
</template>
<style scoped>
.home-container {
min-height: 150px;
background-color: #f2f2f2;
padding: 15px;
}
</style>
AboutView.vue
html
<script>
export default {
name: "AboutView"
}
</script>
<template>
<div class="about-container">
<h3>About组件</h3>
</div>
</template>
<style scoped>
.about-container {
min-height: 150px;
background-color: #f2f2f2;
padding: 15px;
}
</style>
index.js
javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: import.meta.env.BASE_URL,
routes: [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
name: 'home',
component: () => import('../views/HomeView.vue')
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
},
]
})
export default router