vue封装路由的步骤
1、 在router文件目录下,新建两个文件:
homeMoudule.js和config.js
2、在新建homeMoudule.js中, 封装路由代码
import router from './config'
const homeModule = [
router.home,
router.about,
]
export default homeModule;
3、在新建config.js中
import Home from '@/views/Home.vue'
const router = {
home:{
path:'/',
name:'Home',
component:Home
},
about:{
path:"/about",
name:"About",
component:() => import('../views/About.vue')
}
}
export default router;
4、在router文件目录下的index.js中写:
import Vue from 'vue'
import VueRouter from 'vue-router'
import homeModule from './homeModule'
Vue.use(VueRouter)
const routes = [
...homeModule
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
5、在main.js中引入注册
import routerConfig from './router/config';
Vue.prototype.$routerConfig = routerConfig;
6、在组件中使用
<template>
<div>
<button @click="onClick">点击</button>
</div>
</template>
<script>
export default {
methods:{
onClick() {
this.$router.push(this.$routerConfig.about.path)
}
}
}
</script>
<style>
</style>