从0到1构建vueSSR项目之路由的构建

2020-06-13 10:42:17易采站长站整理

src/pages/router/index.js


/**
*
* @method componentPath 路由模块入口
* @param {string} name 要引入的文件地址
* @return {Object}
*/
function componentPath (name = 'home'){
return {
component:() => import(`../${name}/index.vue`)
}
}

export default [
{
path: '/home',
...componentPath(),
children: [
{
path: "vue",
name: "vue",
...componentPath('home/vue')
},
{
path: "vuex",
name: "vuex",
...componentPath('home/vuex')
},
{
path: "vueCli3",
name: "vueCli3",
...componentPath('home/vueCli3')
},
{
path: "vueSSR",
name: "vueSSR",
...componentPath('home/vueSSR')
}
]

}
]

src/router.config.js作为路由的总配置 易于管理


//路由总配置
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
//为什么采用这种做法。
//如果以后有了别的大模块可以单独开个文件夹与pages平级
//再这里导入即可。这样易于管理

// pages
import pages from './pages/router';

export function createRouter() {
return new VueRouter({
mode: 'history',
routes: [
{
path: "*",
redirect: '/home/vue'
},
...pages
] })
}

更新main.js


import Vue from 'vue';
Vue.config.productionTip = false;
import App from './App.vue';
+ import { createRouter } from './router.config.js'
//router store 实例
//这么做是避免状态单例
export function createApp() {
+ const router = createRouter()
const app = new Vue({
+ router,
render: h => h(App)
})
//暴露app,router实例
return { app, router };
}

更新 client.js

由于使用的路由懒加载,所以必须要等路由提前解析完异步组件,才能正确地调用组件中可能存在的路由钩子。


// client.js
import { createApp } from '../main.js';

const { app, router } = createApp();

router.onReady( () => {
app.$mount('#app');
})