vuex是做什么的?
在回答这个问题之前,我们需要明确一点,vuex主要是做什么的。
vuex主要用来组件间数据的传递,还有全局变量的存储(例如user信息)。
vuex的使用并不方便,Getter、Module、Store、Mutation、Action等引入。来回的操作数据,获取数据等,让操作数据变得繁琐。vue2中vuex的使用方式,相信用过vue的同学都清楚。
随着vue3的发布,vue3中还需要用vuex吗。相信很多了解Compositon API的同学能很快反应过来,或许,我们不需要vuex。我们可以很方便的通过Composition API自己去手动创建一个属于自己的‘vuex’,并响应式的去持久化数据。
说干就干,下面我们来一步步去创建vue3中的'vuex'
1、创建state
用vue3创建state思路很简单,用reactive去响应一个对象就可以了,对象里面是我们需要的数据。
import { reactive } from 'vue'
// 定义需要的变量类型的校验
export interface checkState {
user: any
}
// 定义state变量
export const State: checkState = {
user: {}
}
// 将state数据响应式
export function createState() {
return reactive(State)
}
2、创建action
// 定义更新user的方法,方便组件中直接调用
function updateUser(state: checkState) {
return (user: any) => {
state.user = user
}
}
/**
* 创建Action
* @param state
*/
export function createAction(state: checkState) {
return {
updateUser: updateUser(state)
}
}
3、创建自定义的store
import { reactive, readonly } from 'vue'
import { createAction } from './action'
import { createState } from './state'
const state = createState()
const action = createAction(state)
export const createStore = () => {
const store = {
// 设置为readonly是因为我们只能通过action去修改state
state: readonly(state),
action: readonly(action)
}
return store
}
4、在组件中使用我们的store
我们可以将store挂载main.js下,也可以在组件中单独引入
// 访问state
const store = createStore()
store.state.user
// 调用action
const store = createStore()
const user = {
name: '古天乐',
say: '游戏,我只玩蓝月'
}
store.action.updateUser(user)
5、store的持久化存储
之前用vue2时候,会手写个轮子进行持久化,后来用插件vuex-persist.在学习vue3时候,发现了winter老师写的一个基于vue3的响应式localStorage。
源码地址在大圣老师的gihub:github.com/shengxinjin…
写在这里
import {reactive, ref, effect} from "@vue/reactivity"
export default function LocalStorage(key, defaultValue){
let data = reactive({})
Object.assign(data, localStorage[key] && JSON.parse(localStorage[key]) || defaultValue)
effect(() => localStorage[key] = JSON.stringify(data))
return data
}
// 创建state
export const State: checkState = LocalStorage('vuex', {
user: {}
})
我们可以直接持久化整个state,当然也可以将需要持久化的数据单独提出来,然后再合并到state里面。