store模式与vuex状态管理
1、对于简单应用 store 模式
- 集中式状态管理
- action 统一管理 state 的更新,更好地记录 state 的变化和调试
var store = {
debug: true,
state: {
message: 'Hello!'
},
setMessageAction (newValue) {
if (this.debug) console.log('setMessageAction triggered with', newValue)
this.state.message = newValue
},
clearMessageAction () {
if (this.debug) console.log('clearMessageAction triggered')
this.state.message = ''
}
}
var vmA = new Vue({
data: {
// ... privateState
sharedState: store.state
}
})
2、对于大型应用 vuex 状态管理
- 全局单例模式管理状态
- 集中式存储管理应用的所有组件的状态
store 注入根实例,通过 this.$store 访问
// 定义单例store
const store = new Vuex.Store({
mutations: { }, // 全局action
modules: { a: moduleA }
})
// 注入根实例
const app = new Vue({
el: '#app',
store,
components: { Counter },
template:
</span></span><br/><span class="line"><span class="string"> <div class="app"></div>
})
modules 分割模块
// 定义store模块
const moduleA = {
state: { },
mutations: { },
actions: { }
}
// 引用
this.$store.state.a // -> moduleA 的状态
this.$store.state.b // -> moduleB 的状态
state 状态
- 状态存储 state 是响应式的
- 通过 commit 提交 mutation 去改变状态
- 组件可以在计算属性中获取 state
// 引用
this.$store.state.module.selectState
getter 计算属性
// 定义
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
// 通过方法访问,并传参
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
// 引用
this.$store.getters.doneTodos
this.$store.getters.getTodoById(2)
mutation
- 同步函数
- mutation 中变更 state
- 通过 this.$store.commit(‘funName’) 提交 mutation
// 定义
mutations: {
setFlag (state, params) {
state.count++
}
}
// 调用
this.$store.commit('setFlag', params)
action
- 异步函数
- action 中提交 mutation 变更 state
- 通过 this.$store.dispatch() 分发 action
// 定义
actions: {
funcname (context, params) { // {commit, state}
// context.state
// context.getters
context.commit('setFlag')
},
// 返回promise
funcname2 (context) {
return new Promise((resolve, reject) => {
resolve()
}).then().catch()
}
}
// 调用
this.$store.dispatch('funname', params)
await this.$store.dispatch('funcname2')
分类:
javaScript
标签:
javaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)