跳至主要內容
Vue状态仓库持久化

思路

在 Vue 项目中,一般采用 vuex 或者 pinia 去实现全局的状态仓库,

同时在设计时有提供插件方式去控制数据源,可以从插件的方式入手持久化。

Vuex

// store.js
import { createStore } from 'vuex'
import counter from './counter';
import persistPlugin from './persistPlugin'

const store = createStore({
  modules: {
    counter
  },
  plugins: [persistPlugin]
})
export default store;

// persistPlugin.js
const KEY_PREFIX = 'VUEX:STATE:'

export default (context) => {
  const key = `${KEY_PREFIX}${context.store.$id}`
  // 存
  window.addEventListener('beforeunload', () => {
    localStorage.setItem(key, JSON.stringify(context.store.$state))
  })
  // 取
  const value = localStorage.getItem(key)
  if (!value) {
    return
  }
  try {
    const originState = (JSON.parse(value))
    store.replaceState(originState)
  } catch {
    console.log('存储格式有误')
  }
};


石怜安小于 1 分钟VUEVUE
Vue双向绑定

什么是单向绑定

model -> view 数据模型绑定到vue视图上 view -> model 用户视图上更新,同步更新数据模型

MVVM构成

  1. 数据层 model: 存储数据及业务逻辑
  2. 视图层 view: 展示效果
  3. 业务逻辑层 viewModel: 关联数据和视图

数据 视图

  1. observer: 对所有数据的属性进行监听
  2. compiler: 解析器,更新的效果

石怜安小于 1 分钟VUEVUE
Vue 生命周期

每个Vue实例再被创建之前,都会经过一系列的初始化过程,这个过程被称之为vue的生命周期。

其中Vue中包含如下钩子:

VUE2 VUE3 备注
beforeCreate
created
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
activated keep-alive包裹时有效
deactivated keep-alive包裹时有效
errorCapture 捕获异常

下面这张进行了注释官网的生命周期图。

vueLifecycle

石怜安大约 2 分钟VUEVUE
Vue3 工具函数源码解析

Tips

具体文件是 shared.cjs.prod.jsshared.cjs.js 文件下针对源码中的工具函数和较冷门知识点的提取分析。

vue 版本为 3.2.31

常量定义

EMPTY_OBJ、EMPTY_ARR 对象

typescript是通过 readonly 的方式来定义一个冻结对象的类型的, readonly 是只读修饰符。 Object.freeze 冻结对象属性功能。


石怜安大约 18 分钟VUEVUE3VUE