Vue状态管理与与SSR详解

1、vuex简介

1、定义

在vue项⽬中,每个组件的数据都有其独⽴的作⽤域。当组件间需要跨层级或者同层之间频繁传递的时候,数据交互就会⾮常繁琐。vuex的主要作⽤就是集中管理所有组件的数据和状态以及规范数据修改的⽅式。

官方解释:Vuex 是⼀个专为 Vue.js 应⽤程序开发的状态管理模式。它采⽤集中式存储管理应⽤的所有组件的状态,并以相应的规则保证状态以⼀种可预测的⽅式发⽣变化。

2、使用场景

⼀般来讲,是以项⽬中的数据交互复杂程度来决定的。具体包括以下场景:

项⽬组件间数据交互不频繁,组件数量较少:不使⽤状态管理项⽬组件间数据交互频繁,但组件数量较少:使⽤eventBus或者vue store解决项⽬组件间数据交互频繁,组件数量较多:vuex解决

3、核心原理分析

// a.vue <h1>{{ username }}</h1> // b.vue <h2> {{ username }} </h2> /** * 如果 username 需要在每个组件都获取一次,是不是很麻烦,虽然可以通过共同的父级传入,但是不都是这种理想情况 */ 复制代码

Flux 架构主要思想是应用的状态被集中存放到一个仓库中,但是仓库中的状态不能被直接修改,必须通过特定的方式才能更新状态。

vuex基于flux思想为vue框架定制,区分同步和异步,定义两种行为,Actions 用来处理异步状态变更(内部还是调用 Mutations),Mutations 处理同步的状态变更,整个链路应该是一个闭环,单向的,完美契合 FLUX 的思想

「页面 dispatch/commit」-> 「actions/mutations」-> 「状态变更」-> 「页面更新」-> 「页面 dispatch/commit」...

2、vuex五大核心

vue使用单一状态树,单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。用一个对象(主干)就包含了全部的(分支)应用层级状态。每个应用将仅仅包含一个 store 实例对象(主干)。每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state) 。Vuex 和单纯的全局对象有以下两点不同:Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

1、State

当前应⽤状态,可以理解为组件的data⽅法返回的Object

import Vue from vue import Vuex from vuex Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 } }) new Vue({ store, //把store的实例注入所有的子组件,this.$store可访问 render: h => h(App) }).$mount(#app) 复制代码

2、Getters

Getter为state的计算属性,当需要重复对某个数据进⾏某种操作的时候可以封装在getter⾥⾯,当state中的数据改变了以后对应的getter也会相应的改变。

const store = new Vuex.Store({ state: { date: new Date() }, getters: { // Getter 接受 state 作为其第一个参数 weekDate: (state) => { return moment(state.date).format(dddd); }, //Getter 还也可以接收 getters 作为第二个参数 dateLength: (state, getters) => { return getters.weekDate.length; }, //Getter本身为一属性,传参需返回一个函数 weekDate: (state) => (fm) => { return moment(state.date).format(fm ? fm : dddd); } } }) //属性访问 console.log(store.getters.weekDate) console.log(store.getters.dateLength) //方法访问,传参 console.log(store.getters.weekDate(MM Do YY)) 复制代码

3、Mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,必须是同步函数。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type) 和 一个 回调函数 (handler)。回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,第二个参数为载荷(payload)对象。const store = new Vuex.Store({ state: { count: 1 }, mutations: { // 事件类型 type 为 increment increment (state) { state.count++ }, // 添加第二个参数 increment1 (state, payload) { state.count += payload.amount } } }) //参数调用 store.commit(increment) // 1、把载荷和type分开提交 store.commit(increment1, { amount: 10 }) // 2、整个对象都作为载荷传给 mutation 函数 store.commit({ type: increment1, amount: 10 }) //----- 修改参数并使用常量,必须遵循vue规则,使用set或者对象解构 ------- // mutation-types.js export const ADD_MUTATION = SOME_MUTATION // store.js import Vuex from vuex import { ADD_MUTATION } from ./mutation-types const store = new Vuex.Store({ state: { student: { name: 小明, sex: 女 } }, mutations: { // 使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名 [ADD_MUTATION] (state) { Vue.set(state.student, age, 18) //添加age属性 // state.student = { ...state.student, age: 18 } } } }) //使用 import {ADD_PROPERTY} from @/store/mutation-types this.$store.commit(ADD_PROPERTY) 复制代码

4、Actions

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作Action 函数接受一个 context 参数,它与 store 实例有着相同的方法和属性,可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 gettersconst store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit(increment) }, //使用解构简化 increment ({ commit }) { commit(increment) } } }) //分发actions store.dispatch(increment) // 以载荷形式分发 store.dispatch(incrementAsync, { amount: 10 }) // 以对象形式分发 store.dispatch({ type: incrementAsync, amount: 10 }) 复制代码

5、Modules

modules的主要功能是为了防⽌state过于庞⼤和冗余,所以对其进⾏模块化分隔

模块内部的 state 是局部的,只属于模块本身所有,所以外部必须通过对应的模块名进行访问模块内部的 action、mutation 和 getter 默认可是注册在全局命名空间的,通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。//无命名空间 <script> import {mapState, mapMutations} from vuex; export default { computed: { //state不同 ...mapState({ name: state => (state.moduleA.text + 和 + state.moduleB.text) }), }, methods: { //mutation全局 ...mapMutations([setText]), modifyNameAction() { this.setText(); } }, } </script> //使用命名空间 export default { namespaced: true, // ... } <script> import {mapActions, mapGetters} from vuex; export default { computed: { ...mapState({ name: state => (state.moduleA.text + 和 + state.moduleB.text) }), ...mapGetters({ name: moduleA/detail }), }, methods: { ...mapActions({ call: moduleA/callAction }), /* 另外写法 */ ...mapActions(moduleA, { call: callAction }), ...mapActions(moduleA, [callAction]), modifyNameAction() { this.call(); } }, } </script> 复制代码

3、辅助函数

1、mapStates

使用 mapState 辅助函数帮助我们生成计算属性,入参为对象当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from vuex export default { computed: { ...mapState({ // 箭头函数可使代码更简练 a: state => state.a, // 传字符串参数 b // 等同于 `state => state.b` bAlias: b, // 为了能够使用 `this` 获取局部状态 // 必须使用常规函数 cInfo (state) { return state.c + this.info } }), ...mapState([ // 映射 this.a 为 store.state.a a, b, c ]) } 复制代码

2、mapGetters

import { mapGetters } from vuex export default { // ... computed: { ...mapGetters([ doneTodosCount, anotherGetter, // ... ]), ...mapGetters({ doneCount: doneTodosCount }) } } 复制代码

3、mapMutaions

import { mapMutations } from vuex export default { // ... methods: { ...mapMutations([ // 将 `this.increment()` 映射为 // `this.$store.commit(increment)` increment, // `mapMutations` 也支持载荷: // 将 `this.incrementBy(amount)` 映射为 // `this.$store.commit(incrementBy, amount)` incrementBy ]), ...mapMutations({ // 将 `this.add()` 映射为 // `this.$store.commit(increment)` add: increment }) } } 复制代码

4、mapActions

import { mapActions } from vuex export default { // ... methods: { ...mapActions([ // 将 `this.increment()` 映射为 // `this.$store. dispatch(increment)` increment, // `mapActions` 也支持载荷: // 将 `this.incrementBy(amount)` 映射为 // `this.$store. dispatch(incrementBy, amount)` incrementBy ]), ...mapActions({ // 将 `this.add()` 映射为 // `this.$store. dispatch(increment)` add: increment }) } } 复制代码

4、源码解析

1、思路

flux思想问题:在开发中面临最多的场景是状态重复但是不集中,在不同的组件中依赖了同样的状态,重复就会导致不对等的风险。思想:基于 FLUX 的思想,我们设计的状态管理将是中心化的工具,也就是集中式存储管理应用的所有组件的状态,将所有的状态放在一个全局的 Tree 结构中,集中放在一起的好处是可以有效避免重复的问题,也更好的管理,将状态和视图层解耦。解决:使用全局的store对象管理状态和数据,单一状态树状态流转单一流转同步和异步分层:mutations负责同步状态管理、actions负责异步事件(内部通过mutations改变状态)与vue集成通过插件将 vue 集成在一起,通过 mixin 将 $store 这样的快速访问 store 的快捷属性注入到每一个 vue 实例中响应式利用vue的data响应式实现扩展辅助函数模块化插件支持

2、源码解析

1、store注册

/** * store.js - store 注册 */ let Vue // vue 插件必须要这个 install 函数 export function install(_Vue) { Vue = _Vue // 拿到 Vue 的构造器,存起来 // 通过 mixin 注入到每一个vue实例 Vue.mixin({ beforeCreate: vuexInit }) function vuexInit () { const options = this.$options //创建对象入参 // 这样就可以通过 this.$store 访问到 Vuex 实例,拿到 store 了 if (options.store) { this.$store = typeof options.store === function ? options.store() : options.store } else if (options.parent && options.parent.$store) { this.$store = options.parent.$store } } } 复制代码

2、store的响应式

/** * store.js - 实现响应式 */ export class Store { constructor(options = {}) { resetStoreVM(this, options.state) } get state () { return this._vm._data.$$state } } function resetStoreVM(store, state) { // 因为 vue 实例的 data 是响应式的,正好利用这一点,就可以实现 state 的响应式 store._vm = new Vue({ data: { $$state: state } }) } 复制代码

3、衍生数据

/** * store.js - 衍生数据(getters) */ export class Store { constructor(options = {}) { const state = options.state resetStoreVM(this, state) // 我们用 getters 来收集衍生数据 computed this.getters = {} // 简单处理一下,衍生不就是计算一下嘛,传人 state _.forEach(this.getters, (name, getterFn) => { Object.defineProperty(this.getters, name, { get: () => getterFn(this.state) }) }) } get state () { return this._vm._data.$$state } } function resetStoreVM(store, state) { store._vm = new Vue({ data: { $$state: state } }) } 复制代码

4、Actions/Mutations

/** * store.js - Actions/Mutations 行为改变数据 */ export class Store { constructor(options = {}) { const state = options.state resetStoreVM(this, state) this.getters = {} _.forEach(options.getters, (name, getterFn) => { Object.defineProperty(this.getters, name, { get: () => getterFn(this.state) }) }) // 定义的行为,分别对应异步和同步行为处理 this.actions = {} this.mutations = {} _.forEach(options.mutations, (name, mutation) => { this.mutations[name] = payload => { // 最终执行的就是 this._vm_data.$$state.xxx = xxx 这种操作 mutation(this.state, payload) } }) _.forEach(options.actions, (name, action) => { this.actions[name] = payload => { // action 专注于处理异步,这里传入 this,这样就可以在异步里面通过 commit 触发 mutation 同步数据变化了 action(this, payload) } }) } // 触发 mutation 的方式固定是 commit commit(type, payload) { this.mutations[type](payload) } // 触发 action 的方式固定是 dispatch dispatch(type, payload) { this.actions[type](payload) } get state () { return this._vm._data.$$state } } function resetStoreVM(store, state) { store._vm = new Vue({ data: { $$state: state } }) } 复制代码

5、分形,拆分出多个 Module

// module 可以对状态模型进行分层,每个 module 又含有自己的 state、getters、actions 等 // 定义一个 module 基类 class Module { constructor(rawModule) { this.state = rawModule || {} this._rawModule = rawModule this._children = {} } getChild (key) { return this._children[key] } addChild (key, module) { this._children[key] = module } } // module-collection.js 把 module 收集起来 class ModuleCollection { constructor(options = {}) { this.register([], options) } register(path, rawModule) { const newModule = new Module(rawModule) if (path.length === 0 ) { // 如果是根模块 将这个模块挂在到根实例上 this.root = newModule } else { const parent = path.slice(0, -1).reduce((module, key) => { return module.getChild(key) }, this.root) parent.addChild(path[path.length - 1], newModule) } // 如果有 modules,开始递归注册一波 if (rawModule.modules) { _.forEach(rawModule.modules, (key, rawChildModule) => { this.register(path.concat(key), rawChildModule) }) } } } // store.js 中 export class Store { constructor(options = {}) { // 其余代码... // 所有的 modules 注册进来 this._modules = new ModuleCollection(options) // 但是这些 modules 中的 actions, mutations, getters 都没有注册,所以我们原来的方法要重新写一下 // 递归的去注册一下就行了,这里抽离一个方法出来实现 installModule(this, this.state, [], this._modules.root); } } function installModule(store, state, path, root) { // getters const getters = root._rawModule.getters if (getters) { _.forEach(getters, (name, getterFn) => { Object.defineProperty(store.getters, name, { get: () => getterFn(root.state) }) }) } // mutations const mutations = root._rawModule.mutations if (mutations) { _.forEach(mutations, (name, mutation) => { let _mutations = store.mutations[name] || (store.mutations[name] = []) _mutations.push(payload => { mutation(root.state, payload) }) store.mutations[name] = _mutations }) } // actions const actions = root._rawModule.actions if (actions) { _.forEach(actions, (name, action) => { let _actions = store.actions[name] || (store.actions[name] = []) _actions.push(payload => { action(store, payload) }) store.actions[name] = _actions }) } // 递归 _.forEach(root._children, (name, childModule) => { installModule(this, this.state, path.concat(name), childModule) }) } 复制代码

6、插件机制

(options.plugins || []).forEach(plugin => plugin(this)) 复制代码

以上只是以最简化的代码实现了 vuex 核心的 state module actions mutations getters 机制,如果对源代码感兴趣,可以看看若川的文章

二、Vue-ssr

参考资料:

1、vue-ssr官网指南

1、模版渲染

1、实例render属性

渲染函数:(createElement: () => VNode, [context]) => VNode入参:接收一个 createElement 方法作为第一个参数用来创建 VNode出参:VNode对象如果组件是一个函数组件,渲染函数还会接收一个额外的 context 参数,为没有实例的函数组件提供上下文信息Vue 选项中的 render 函数若存在,则 Vue 构造函数不会从 template 选项或通过 el 选项指定的挂载元素中提取出的 HTML 模板编译渲染函数,注意:.vue组件中temlate部分会渲染,需去除。组件树中的所有 VNode 必须是唯一的,需要重复很多次的元素/组件,你可以使用工厂函数来实现Vue.component(anchored-heading, { render: function (createElement) { return createElement( h + this.level, // 标签名称 this.$slots.default // 子节点数组 ) }, props: { level: { type: Number, required: true } } }) /* 渲染模版如下: <script type="text/x-template" id="anchored-heading-template"> <h1 v-if="level === 1"> <slot></slot> </h1> <h2 v-else-if="level === 2"> <slot></slot> </h2> </script> */ //VNode唯一,使用工程函数实现 { render: function(h){ return h(div, Array.apply(null, { length: 20 }).map(function () { return createElement(p, hi) }) ) } } 复制代码

2、createElement函数

通常将 h 作为 createElement 的别名

/** 创建虚拟dom函数: * createElement({String | Object | Function}, [object], {string | array}): VNode */ createElement( //1、必输:{String | Object | Function} //HTML 标签名、组件选项对象,或者resolve了任何一种的一个async函数 div, //2、可选 {Object} //与模板中 attribute 对应的数据对象 { // 与 `v-bind:class` 的 API 相同, // 接受一个字符串、对象或字符串和对象组成的数组 class: { foo: true, bar: false }, // 与 `v-bind:style` 的 API 相同, // 接受一个字符串、对象,或对象组成的数组 style: { color: red, fontSize: 14px }, // 普通的 HTML attribute attrs: { id: foo }, // 组件 prop props: { myProp: bar }, // DOM property domProps: { innerHTML: baz }, // 事件监听器在 `on` 内, // 但不再支持如 `v-on:keyup.enter` 这样的修饰器。 // 需要在处理函数中手动检查 keyCode。 on: { click: this.clickHandler }, // 仅用于组件,用于监听原生事件,而不是组件内部使用 // `vm.$emit` 触发的事件。 nativeOn: { click: this.nativeClickHandler }, // 自定义指令。注意,你无法对 `binding` 中的 `oldValue` // 赋值,因为 Vue 已经自动为你进行了同步。 directives: [ { name: my-custom-directive, value: 2, expression: 1 + 1, arg: foo, modifiers: { bar: true } } ], // 作用域插槽的格式为 // { name: props => VNode | Array<VNode> } scopedSlots: { default: props => createElement(span, props.text) }, // 如果组件是其它组件的子组件,需为插槽指定名称 slot: name-of-slot, // 其它特殊顶层 property key: myKey, ref: myRef, // 如果你在渲染函数中给多个元素都应用了相同的 ref 名, // 那么 `$refs.myRef` 会变成一个数组。 refInFor: true }, //3、可选:{String | Array} //子级虚拟节点 (VNodes),由 `createElement()` 构建而成,也可以使用字符串来生成“文本虚拟节点” [ 先写一些文字, createElement(h1, 一则头条), createElement(MyComponent, { props: { someProp: foobar } }) ] ) 复制代码

3、Vnode对象

// VNode对象 { asyncFactory: asyncMeta: children: (2) [VNode, VNode] componentInstance: componentOptions: context: VueComponent {_uid: 4, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …} data: { attr: { id: div-id, name: div-name } }, elm: div fnContext: fnOptions: fnScopeId: isAsyncPlaceholder: false isCloned: false isComment: false isOnce: false isRootInsert: true isStatic: false key: //key属性 ns: parent: VNode {tag: "vue-component-92", data: {…}, children: , text: , elm: div, …} raw: false tag: "div" //组件名 text: child: [[Prototype]]: Object } 复制代码

4、模版渲染

1、v-if/v-for

使用if和map函数实现

<ul v-if="items.length"> <li v-for="item in items">{{ item.name }}</li> </ul> <p v-else>No items found.</p> <!-- 如下渲染函数实现 --> <!-- { render(h){ if(this.items.length){ return h(ul, this.items.map(item => { return h(li, item.name) }) )else{ return h(p, No items found.) } } } --> 复制代码

2、v-model

自己实现相关逻辑

<input v-model="value"></input> <!-- 如下渲染函数实现 --> <!-- { props:[value], render(h){ let self = this return h(input, { //DOM property domPops:{ value: self.value }, on: { input: function(event){ self.$emit(input, event.target.value) } } }) } } --> 复制代码

3、事件&按键修饰符

.passive/.capture/.once:提供相应前缀使用.passive:前缀&.capture:前缀!.once:前缀~.capture.once或.once.capture:前缀~!其他修饰符号可以调用私有方法//.passive .capture .once on: { !click: this.doThisInCapturingMode, ~keyup: this.doThisOnce, ~!mouseover: this.doThisOnceInCapturingMode } //其他修饰符 on: { keyup: function (event) { //.self // 如果触发事件的元素不是事件绑定的元素 // 则返回 if (event.target !== event.currentTarget) return //.shift | .enter/.13 // 如果按下去的不是 enter 键或者 // 没有同时按下 shift 键 // 则返回 if (!event.shiftKey || event.keyCode !== 13) return //.stop // 阻止 事件冒泡 event.stopPropagation() //.prevent // 阻止该元素默认的 keyup 事件 event.preventDefault() // ... } } 复制代码

4、插槽

静态插槽:this.$slots作用域插槽:this.$scopedSlots组件中传递作用域插槽:scopedSlots属性<!-- <div><slot></slot></div> --> render: function(createElement){ return createElement(div, this.$slots.default) } <!-- <div><slot :text="message"></slot></div> --> render: function(createELement){ return createElement(div, this.$scopedSlots.default({ text: this.message })) } <!-- <div> <child v-slot="props"> <span>{{props.text}}</span> </child> </div> --> render: function(createElement){ return createElement(div, [ createElement(child, { scopedSlots: { // 在数据对象中传递 `scopedSlots` // 格式为 { name: props => VNode | Array<VNode> } default: function(props){ return createElement(span, props.text) } } }) }) } 复制代码

5、jsx

使用babel插件,渲染函数使用h

import AnchoredHeading from ./AnchoredHeading.vue new Vue({ el: #demo, render: function (h) { return ( <AnchoredHeading level={1}> <span>Hello</span> world! </AnchoredHeading> ) } }) 复制代码

2、csr与ssr

首先让我们看看 CSR 的过程(划重点,浏览器渲染原理基本流程)

1、csr

浏览器渲染原理基本流程浏览器通过请求得到一个HTML文本渲染进程解析HTML文本,构建DOM树解析HTML的同时,如果遇到内联样式或者样式脚本,则下载并构建样式规则(stytle rules),若遇到JavaScript脚本,则会下载执行脚本。DOM树和样式规则构建完成之后,渲染进程将两者合并成渲染树(render tree)渲染进程开始对渲染树进行布局,生成布局树(layout tree)渲染进程对布局树进行绘制,生成绘制记录渲染进程的对布局树进行分层,分别栅格化每一层,并得到合成帧渲染进程将合成帧信息发送给GPU进程显示到页面中流程:加载html文件、下载资源、脚本解析、运行往div中插入元素,渲染页面特点:不利用seo、首屏加载时间长(time-to-content)

很容易发现,CSR 的特点就是会在浏览器端的运行时去动态的渲染、更新 DOM 节点,特别是 SPA 应用来说,其模版 HTML 只有一个 DIV,然后是运行时(React,Vue,Svelte 等)动态的往里插入内容,这样的话各种 BaiduSpider 拿不到啥有效信息,自然 SEO 就不好了,项目一旦复杂起来, bundle 可能超乎寻常的大...这也是一个开销。

2、ssr

服务端完成了渲染过程,将渲染完成的 HTML 字符串或者流返回给浏览器,就少了脚本解析、运行这一环节,理论上 FP 表现的更佳,SEO 同样提升。缺点:

复杂,同构项目的代码复杂度直线上升,因为要兼容两种环境对服务端的开销大,既然 HTML 都是拼接好的,那么传输的数据肯定就大多了,同时,拿 Node 举例,在处理 Computed 密集型逻辑的时候是阻塞的,不得不上负载均衡、缓存策略等来提升CI/CD 更麻烦了,需要在一个 Server 环境,比如 Node

一般来说,ToB 的业务场景基本不需要 SSR,需要 SSR 的一定是对首屏或者 SEO 有强诉求的,部分场景可使用预渲染。

CSR 和 SSR ,我们现今常见的渲染方案有6-7种:

3、同构直出

一份代码,既可以客户端渲染,也可以服务端渲染,采用水合 hydration 方案,对 FP 有帮助,但是不能提升 TTI(可交互时间)。

1、原理

ssr渲染页面整体结构提升fp,在此基础上csr中添加事件等操作完成最终可交互的页面。ssr只⽀持beforeCreate、created⽣命周期,csr中支持所有操作建议放置在mounted事件后。csr为页面 = 模块 + 数据,应用 = 路由 + 页面,同构就是同构路由、模版、数据。

2、实践

css如何处理:服务端的 webpack 不用关注 CSS,客户端会打包出来的,到时候推 CDN,然后修改 public path 即可服务端的代码不需要分 chunk,Node 基于内存一次性读取反而更高效如果有一些方法需要在特定的环境执行,比如客户端环境中上报日志,可以利用 beforeMouted 之后的生命周期都不会在服务端执行这一特点,当然也可以使用 isBrowser 这种判断CSR 和 SSR 的切换和降级// 总有一些奇奇怪怪的场景,比如就只需要 CSR,不需要 SSR // 或者在 SSR 渲染的时候出错了,页面最好不要崩溃啊,可以降级成 CSR 渲染,保证页面能够出来 // 互相切换的话,总得有个标识是吧,告诉我用 CSR 还是 SSR // search 就不错,/demo?ssr=true module.exports = function(req, res) { if(req.query.ssr === true){ const context = { url: req.url } renderer.renderToString(context, (err, html) => { if(err){ res.render(demo) // views 文件下的 demo.html } res.end(html) }) } else { res.render(demo) } } 复制代码Axios 封装,至少区分环境,在客户端环境是需要做代理的

3、Vue-ssr 优化方案

页面级别的缓存,比如 nginx micro-caching设置 serverCacheKey,如果相同,将使用缓存,组件级别的缓存CGI 缓存,通过 memcache 等,将相同的数据返回缓存一下,注意设置缓存更新机制流式传输,但是必须在asyncData 之后,否则没有数据,说明也可能会被 CGI 耗时阻塞(服务端获取数据后,加载至全局,客户端直接使用即可)分块传输,这样前置的 CGI 完成就会渲染输出JSC,就是不用 vue-loader,最快的方案

4、代码实战

1、Npm Script

"build": "npm run build:client && npm run build:server", "server": "cross-env NODE_ENV=production nodemon ./server/index.js", "dev:server": "cross-env NODE_ENV=development nodemon ./server/index.js", "build:client": "vue-cli-service build", "build:server": "cross-env VUE_ENV=server vue-cli-service build--no-clean", "dev:client": "vue-cli-service serve" vue inspect --mode "production" > output.js 复制代码

2、Project Info

cli: vue-cli @vue/cli 4.5.13ui: element-uistate: vuexrouter: vue-router hash modelang: vue-i18nhttp: axiospackage manager: npmunit-test: jest、mocha静态检查和格式化工具: eslint、prettierMock:mockjsserver: koa、koa-mount、koa-router、koa-static、xssvue plugins: vue-infinite-loading、vue-meta、vue-server-renderer(ssr)tools: reset-css、cross-env(环境变量配置)推荐服务端渲染框架:nuxt.js

3、Project Structure

├── mock//mock脚步及数据 ├── node_modules//模块内容 ├── public//静态资源文件,不参与webpack打包,包含server.html和index.html ├── server//web服务器代码,实现ssr ├── utils //server和client公用utils工具类 ├── src //源代码目录 │ ├── assets//静态资源,被webpack打包 │ ├── components//公用组件位置 │ ├── directives//全局指令 │ ├── lang//语言文件 │ ├── router//router │ ├── store //store │ ├── utils //工具方法,request为axios库文件 │ ├── views //按照功能板块划分出的页面 │ | └── home//子功能模块 │ | ├── store //子功能模块数据 │ | ├── router//子功能模块路由 │ | ├── i18n//子功能模块语言 │ | └── mock//子功能模块mock数据 │ ├── App.vue //入口页面 │ ├── app.js//应用入口文件,app工程函数 │ ├── client-entry.js//客户端入口文件,初始化store、挂载dom │ └── server-entry.js//服务端入口文件,返回promise,处理路由、挂载store ├── test//单元测试 ├── .browserslistrc //browserify配置 ├── .eslintrc.js//eslint配置 ├── .babel.config.js//bable配置 ├── package.json//npm包配置 ├── nodemon.json//nodemon配置文件,设置node环境变量 ├── vue.config.js //vue配置,区分server和client └── README.md //项目说明文件 复制代码

4、SSR改造步骤

相关插件及库安装,配置打包package.json脚本server:koa、koa-mount、koa-router、koa-static、xss、nodemonvue-ssr:vue-server-renderer(使用server-plugin和client-plugin)环境变量配置:cross-env NODE_ENV=production 或者 nodemon.jsonserver代码添加:koa代码启动:监听端口静态资源:使用koa-static、koa-mount挂载静态服务器api接口:使用koa-mount挂载api接口,app.use(KoaMount("/api", ApiRequest))路由挂载:返回ssr渲染页面使用koa-router启动路由,监听任何根路径,返回promise:router.get(/(.*), async ctx => {})使用vue-server-renderer插件,渲染返回最终的ssr渲染页面使用vue-ssr-server-manifest.json渲染页面,使用vue-ssr-client-manifest.json激活页面const VueServerRenderer = require("vue-server-renderer"); //插件 const serverBundle = require("../dist/vue-ssr-server-bundle.json"); //服务端bundle const clientManifest = require("../dist/vue-ssr-client-manifest.json");//客户端激活bundle const template = fs.readFileSync( //渲染模版 path.resolve(__dirname, "../dist/server.html"), "utf-8" ); router.get("/(.*)", async (ctx) => { ctx.body = await new Promise((resolve, reject) => { const render = VueServerRenderer.createBundleRenderer(serverBundle, { runInNewContext: false, template, clientManifest, //注入客户端js,script标签 }); //渲染函数入参context,访问的路径path传入渲染函数中,获取ssr渲染页面 const context = { url: ctx.path }; render.renderToString(context, (err, html) => { if (err) { reject(err); } resolve(html); }); }); }); 复制代码原client代码改造为同构代码添加server.html入口模版,用于服务器渲染拆分webpack入口:server-entry.js、client-entry.js,修改webpack配置client-entry.js: 挂载dom,同步服务器端store数据server-entry.js: 返回promise函数,resolve(app),处理路由和store数据vue.config.js: 区分server和clientserver:服务端ajax请求必须是是绝对路径,添加DefinePlugin插件server和client区分:entry、target、output、server添加server-plugin,client添加client-pluginserver:node端不需要打包node_modules⾥⾯的模块但允许css文件,externals = nodeExternals({allowlist: /.css$/})其他优化:vue-loader的cache处理、extract-css的bug修复//server-entry.js export default (context) => { return new Promise((resolve, reject) => { const { app, router, store } = createVueApp(); const meta = app.$meta(); // 根据服务端传入的url,设置当前客户端的url router.push(context.url); // 有可能是异步路由,要等待异步路由和钩子函数解析完 router.onReady(() => { // 等待serverPrefetch中的数据返回收,设置state context.rendered = () => { // After the app is rendered, our store is now // filled with the state from our components. // When we attach the state to the context, and the `template` option // is used for the renderer, the state will automatically be // serialized and injected into the HTML as `window.__INITIAL_STATE__`. context.state = store.state; context.meta = meta; }; resolve(app); }, reject); }); }; //client-entry.js if (window.__INITIAL_STATE__) { store.replaceState(window.__INITIAL_STATE__); } app.$mount("#app"); 复制代码vue实例拆分:app.js,使用工程函数,访问服务器多次请求同实例污染,下同router实例拆分:使用工厂函数路由如何处理:server代码中通过context传入url,打包入口server-entry.js中传入router.push(context.url);异步路由处理:使用router.onReady(() => {resolve(app)}, reject)store实例拆分:使用工厂函数view页面数据处理:添加serverPrefetch服务端数据获取函数,可在服务器获取数据,注意:老api为asycndata只能在根组件使用、serverPrefect新api任意组件使用

5、SSR相关问题

如何等待异步请求的数据返回后,再渲染⻚⾯;客户端中的store如何同步服务端的数据?组件中添加serverPrefetch选项,返回promise服务端⼊⼝server-entry.js添加context.rendered回调,渲染完成后执⾏,自动序列化注入window.__INITIAL_STATE__变量设置context.state = store.state客户端⼊⼝获取window.__INITIAL_STATE__,设置store初始状态meta、title等标签如何注⼊?使用vue-meta插件:vue.use(vueMeta)主组件App.vue,使用metaInfo添加meta和title子组件中可使用metaInfo函数,覆盖默认的metaInfoserver-entry中拿到meta,并将其传⼊到context中,渲染server.html中的meta信息<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> {{{ meta.inject().title.text() }}} {{{ meta.inject().meta.text() }}} </head> <body> <!--vue-ssr-outlet--> </body> </html> 复制代码服务端渲染会执⾏的⽣命周期: 只执⾏beforeCreate created,不要在这两个⽣命周期⾥⾯添加定时器或者使⽤window等服务器本地开发热更新:webpack配置读取在内存中

最后

如果你觉得此文对你有一丁点帮助,点个赞。或者可以加入我的开发交流群:相互学习,我们会有专业的技术答疑解惑

如果你觉得这篇文章对你有点用的话,麻烦请给我们的开源项目点点star:不胜感激 !

PHP学习手册:技术交流论坛: