之前有寫過用vue.config.js中的pages節點配置多頁,但是這樣,每個頁面都要有一個入口文件和入口vue(如app.js 和app.vue),
對於多個同樣的項目,尤其是要利用到共同的通用配置,其實只需要寫一個入口文件,入口vue,每個頁面個性化寫自己的頁面,可以充分做到既通用又模塊化
1、在src目錄下新建router文件夾,文件夾下新建index.js,index.js中寫每個頁面的路徑
import Vue from 'vue'
import Router from 'vue-router'
/********************* 地圖頁面開始 ******************************** */
//地圖頁面
import map from '../components/map/index.vue';
// 地圖監控頁面
import flightMap from '../components/flightMap/index.vue';
/********************* 地圖頁面結束 ******************************** */
Vue.use(Router);
const routes = [{
path: '/',
redirect: '/map', //必須有配置這個路徑,否則轉發無效
component: map,
meta: { requiresAuth: true },
},
{
path: '/map',
name: 'map',
component: map,
meta: { requiresAuth: true },
},
{
path: '/flightMap',
name: 'flightMap',
component: flightMap,
meta: { requiresAuth: true },
}
]
const router = new Router({
mode: 'history',
// base: 'D-Square',
routes
});
export default router;
2、在src/main.js中引入路由
import Vue from 'vue'
import App from './App'
new Vue({
el: '#app',
router,
render: h => h(App)
})
3、在src/App.vue中引入router-view
<template>
<div id="app">
<router-view v-if="isRouterAlive" class="view"></router-view>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: 'App',
provide () {
return {
reload: this.reload,
}
},
data(){
return {
isRouterAlive: true
}
},
mounted () {
},
methods: {
reload(){
this.isRouterAlive = false;
this.$nextTick(()=>{
this.isRouterAlive = true;
})
}
}
}
</script>
<style>
#app{
width: 100%;
height: 100%;
}
</style>
// WEBPACK FOOTER //
// src/App.vue
4、在src/components下分別寫每個頁面
如map頁面,新建map文件夾,新建index.vue(名字可隨意起,但是要和src/router/index.js中引入的組件名稱一致)
5、npm run serve 編譯後根據路徑訪問某個頁面