加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

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

发布时间:2019-03-24 14:45:38 所属栏目:优化 来源:counterxing
导读:副标题#e# 随着各大前端框架的诞生和演变,SPA开始流行,单页面应用的优势在于可以不重新加载整个页面的情况下,通过ajax和服务器通信,实现整个Web应用拒不更新,带来了极致的用户体验。然而,对于需要SEO、追求极致的首屏性能的应用,前端渲染的SPA是糟糕

对于旧项目迁移到SSR肯定会经历的问题,一般为在项目入口处或是created、beforeCreate生命周期使用了DOM操作,或是获取了location对象,通用的解决方案一般为判断执行环境,通过typeof window是否为'undefined',如果遇到必须使用location对象的地方用于获取url中的相关参数,在ctx对象中也可以找到对应参数。

  •  vue-router报错Uncaught TypeError: _Vue.extend is not _Vue function,没有找到_Vue实例的问题:

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

  1. VueRouter.prototype.init = function init (app /* Vue component instance */) {  
  2.     var this$1 = this;  
  3.   process.env.NODE_ENV !== 'production' && assert(  
  4.     install.installed,  
  5.     "not installed. Make sure to call `Vue.use(VueRouter)` " +  
  6.     "before creating root instance."  
  7.   );  
  8.   // ...  
  •  服务端无法获取hash路由的参数

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

  •  接口处获取不到cookie的问题:

由于客户端每次请求都会对应地把cookie带给接口侧,而服务端Web Server Frame作为代理服务器,并不会每次维持cookie,,所以需要我们手动把

cookie透传给接口侧,常用的解决方案是,将ctx挂载到全局状态中,当发起异步请求时,手动带上cookie,如下代码所示:

  1. // createStore.js  
  2. // 在创建全局状态的函数`createStore`时,将`ctx`挂载到全局状态  
  3. export function createStore({ ctx }) {  
  4.     return new Vuex.Store({  
  5.         state: {  
  6.             ...state,  
  7.             ctx,  
  8.         }, 
  9.          getters,  
  10.         actions,  
  11.         mutations,  
  12.         modules: {  
  13.             // ...  
  14.         },  
  15.         plugins: debug ? [createLogger()] : [],  
  16.     });  

当发起异步请求时,手动带上cookie,项目中使用的是Axios:

  1. // actions.js  
  2. // ...  
  3. const actions = {  
  4.   async getUserInfo({ commit, state }) {  
  5.     let requestParams = {  
  6.       params: {  
  7.         random: tool.createRandomString(8, true),  
  8.       },  
  9.       headers: {  
  10.         'X-Requested-With': 'XMLHttpRequest',  
  11.       },  
  12.     };  
  13.     // 手动带上cookie  
  14.     if (state.ctx.request.headers.cookie) {  
  15.       requestParams.headers.Cookie = state.ctx.request.headers.cookie;  
  16.     }  
  17.     // ...  
  18.     let res = await Axios.get(`${requestUrlOrigin}${url.GET_A}`, requestParams);  
  19.     commit(globalTypes.SET_A, {  
  20.       res: res.data,  
  21.     });  
  22.   }  
  23. };  
  24. // ... 
  •  接口请求时报connect ECONNREFUSED 127.0.0.1:80的问题

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读