网站建设维护的职位,怎样才能建设一歌网站,php网站建设找哪家好,深圳做网站的引用自 摸鱼wiki 1. vuex
vuex是一个前端广泛流行的状态管理库#xff0c;主要由以下几大模块组成#xff1a;
state#xff1a;状态存储getter#xff1a;属性访问器mutation#xff1a;可以理解为一个同步的原子性事务#xff0c;修改state状态action#xff1a;触发… 引用自 摸鱼wiki 1. vuex
vuex是一个前端广泛流行的状态管理库主要由以下几大模块组成
state状态存储getter属性访问器mutation可以理解为一个同步的原子性事务修改state状态action触发mutation可进行异步操作module模块化
2. 类vuex状态库实现
得益于vue在2.6.0版本推出的observable API我们可以用来监听对象的数据变化实现一个简易的状态管理
2.1 自定义状态库 CustomStore 实现
主要实现了类vuex中的state、mutation、action部分
import Vue from vue;
import { updateUserAPI } from api;class CustomStore {state: {user: string,id: number}constructor() {const state Vue.observable({user: ,id: 0,});this.state state;}// mutationsetUser(user: string) {this.state.user user;}setId(id: number) {this.state.id id;}// actionasync updateUser(user: string) {try {await updateUserAPI(user);this.setUser(user);} catch (e) {console.error(e);}}
}export const customStore new CustomStore();2.2 在组件中调用
通过computed属性充当getter的角色监听state的变化并根据需要调整格式化返回值
templatediv clickonClick{{ id }}:{{ user }}/div
/templatescript langts setup
import { customStore } from CustomStore
import { computed } from vueconst id computed(() customStore.state.id)
const user computed(() customStore.state.user)function onClick() {customStore.updateUser(test)
}
/script