Vue服务端渲染实践之Web应用首屏耗时最优化方案

2020-06-14 06:25:04易采站长站整理
实例的问题:

通过查看

Vue-router
源码发现没有手动调用
Vue.use(Vue-Router);
。没有调用
Vue.use(Vue-Router);
在浏览器端没有出现问题,但在服务端就会出现问题。对应的
Vue-router
源码所示:


VueRouter.prototype.init = function init (app /* Vue component instance */) {
var this$1 = this;

process.env.NODE_ENV !== 'production' && assert(
install.installed,
"not installed. Make sure to call `Vue.use(VueRouter)` " +
"before creating root instance."
);
// ...
}

服务端无法获取

hash
路由的参数

由于

hash
路由的参数,会导致
vue-router
不起效果,对于使用了
vue-router
的前后端同构应用,必须换为
history
路由。

接口处获取不到

cookie
的问题:

由于客户端每次请求都会对应地把

cookie
带给接口侧,而服务端
Web Server Frame
作为代理服务器,并不会每次维持
cookie
,所以需要我们手动把
cookie
透传给接口侧,常用的解决方案是,将
ctx
挂载到全局状态中,当发起异步请求时,手动带上
cookie
,如下代码所示:


// createStore.js
// 在创建全局状态的函数`createStore`时,将`ctx`挂载到全局状态
export function createStore({ ctx }) {
return new Vuex.Store({
state: {
...state,
ctx,
},
getters,
actions,
mutations,
modules: {
// ...
},
plugins: debug ? [createLogger()] : [],
});
}

当发起异步请求时,手动带上

cookie
,项目中使用的是
Axios


// actions.js

// ...
const actions = {
async getUserInfo({ commit, state }) {
let requestParams = {
params: {
random: tool.createRandomString(8, true),
},
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
};

// 手动带上cookie
if (state.ctx.request.headers.cookie) {
requestParams.headers.Cookie = state.ctx.request.headers.cookie;