Vue中路由封装重复使用

路由封装

在router中创建两个文件 config.js和homeMoudule.js
1、在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')
  }, 
   demon:{
    path:"/demon",
    name:"demon",
    component:() => import('../views/Demon.vue')
  }
}

export default router;

2、在homeModule中引用
import router from “./config”;

const homeMoudule = [
    router.home,
    router.about,
    router.demon
]

export default homeMoudule

3、在index.js中引入homeModule.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

4、在main.js中配置config.js

import routerConfig from './router/config';
Vue.prototype.$routerConfig = routerConfig;

5、在home 中使用

<template>
  <div>
       <button @click="onClick">点击</button>
  </div>
</template>

<script>
export default {
	data(){
	return{
	}
	},
	 methods:{
    onClick(){
      this.$router.push(this.$routerConfig.about.path)
    }
  },
}
</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/weixin_48193717/article/details/107006486