Vue3 的轻量级的状态管理。
简称:nf-state
基于 reactive, 完全发挥 composition API 的特点,简单快捷,好用。
参考了一下 Vuex 和 Pinia,去掉了自己不需要的功能,以及不喜欢的方式,按照个人喜好设计需要的功能。
- reactive:基础状态,不需要整体变更状态
- useState:简单状态,可以整体赋值
- useModel:适用于表单,可以 reset
- useList:适用于数组
- shallowRef:只关注整体赋值的数组
- vite5
- Vue3.5 (composition API)
- lib 状态管理的源码
- src 状态管理的使用demo
- distp 在线演示的代码
https://gitee.com/naturefw-code/nf-rollup-state
https://naturefw-code.gitee.io/nf-rollup-state/
https://nfpress.gitee.io/doc-nf-state
npm i @naturefw/nf-state
或者
yarn add @naturefw/nf-state
- 简单状态
import { useState, lineCode } from '@naturefw/nf-state'
// 其实就是一个 reactive
const person = useState({
name: '基础类型,初始值',
age:20
})
// 代码定位,当出错的时候使用,平时不需要使用。
// 开发模式有效,生产模式无效
lineCode(person)
// 整体赋值
person.$state = {
name: 'state 赋值aaa',
age: 30
}
// 局部赋值
person.$patch({
name: 'state 赋值aaa'
})
- 表单 model
import { useModel } from '@naturefw/nf-state'
// 为了便于实现 reset ,需要使用函数的形式
const person = useModel<Person>(() => {
return {
name: 'Model的演示',
age: 10,
region: '',
date1: '',
}
})
// 重置
person.$reset()
//
- 数组
import { useList } from '@naturefw/nf-state'
// 其实就是一个 reactive
const list = useList([{
name: '深层初始'
}])
// 整体赋值
list.value = [ {name: '整体赋值' + index++}]
// 或者
list.$state = [ {name: '整体赋值' + index++}]
- 全局状态
可以使用全局变量的方式实现。
- 定义状态的文件
export default function regUserState() {
// 定义内部成员
// 内部使用的用户状态
const user = reactive({
name: '没有登录',
isLogin: false,
power: {
modules: [] as Array<number | string>
}
})
// 登录用的函数,仅示意,不涉及细节
const login = () => {
// 模拟登录
user.name = '张三'
user.isLogin = true
user.power.modules.length = 0
user.power.modules = [...[1,2,3]]
}
// 模拟退出,仅示意
const logout = () => {
// 模拟退出
user.name = '已经退出'
user.isLogin = false
user.power.modules.length = 0
}
// 返回 数据和状态
return {
user: readonly(user),
// ...toRefs(readonly(user)),
login,
logout,
}
}
- 整合文件
// 加载用户状态
import regUserState from './state-user'
// 创建用户状态
const userState = regUserState()
// 记入全局状态
const store = {
userState
}
// 变成全局状态
export default store
- 局部状态
使用依赖注入的方式,实现局部状态。
基本用法就是这些了,其他的就是各种灵活应用。