博客
关于我
vuex最简单、最详细的入门文档
阅读量:496 次
发布时间:2019-03-07

本文共 1668 字,大约阅读时间需要 5 分钟。

Vuex 应用实例解析

安装与初始化

安装 vuex 包括两步:首先通过 npm 安装,接着在主应用文件中初始化 store。

prenpm install vuex --save/template

在 main.js 中加入以下代码:

preimport vuex from 'vuex'Vue.use(vuex)const store = new Vuex.Store({ state: { show: false }})/template

最后,将 store 对象传递给 Vue 实例:

prenew Vue({ el: '#app', store, // 其他配置})/template

模块化管理状态

将 store 分离到 src/directory 下的 store/index.js 中:

preimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({ modules: { dialog: dialogStore // 假设 dialogStore 是单独管理对话框的 store }})/template

创建子组件专属的 store

创建 dialog_store.js:

preexport default { state: { show: false }}/template

在主 store 中引用:

premodules: { dialog: dialogStore}/template

改写传统的状态管理方式

不再需要直接修改父组件传递的参数,而是通过 vuex store 来统一管理状态:

父组件按钮点击改用:

pre@click="$store.commit('switch_dialog')"/template

子组件引用 store:", state 进行计算:

pretemplate Eisenhower:projectId康tel:visible.sync="$store.state.dialog.show"/template

mutations 与 actions 分别处理

mutations 用于直接修改状态,简单易懂;actions 用于多次调用 mutations,保持操作的单一性。

在 dialog_store.js 中:

preexport default { state: { show: false }, mutations: { switchDialog(state) { state.show = !state.show } }, actions: { switchDialog(context) { context.commit('switchDialog') } }}/template

getters 提取计算状态

复杂的状态计算转化为 getters,方便多处复用。

preexport default { state: { show: false }, getters: { notShow(state) { return !state.show } }, // 其他功能}/template

Vuex 此法优于直接使用 state

避免了 state 直接暴露在组件中,提升代码模块化程度:

在组件中改用 mapState 提取状态:

pre
/template

总结 Plus 小贴士

1. mapState、mapActions、mapGetters 提供更简洁的写法,避免繁琐

2. mutations 里的操作必须同步,不能有异步操作(官方建议)

3. 状态管理要按模块化分开,维护更方便

4. 使用 tools: ' preload' 可提升初始加载速度

转载地址:http://sazjz.baihongyu.com/

你可能感兴趣的文章
Netty工作笔记0025---SocketChannel API
查看>>
Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
查看>>
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0057---Netty群聊系统服务端
查看>>
Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
查看>>
Netty工作笔记0063---WebSocket长连接开发2
查看>>
Netty工作笔记0070---Protobuf使用案例Codec使用
查看>>
Netty工作笔记0077---handler链调用机制实例4
查看>>
Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
查看>>
Netty工作笔记0085---TCP粘包拆包内容梳理
查看>>
Netty常用组件一
查看>>
Netty常见组件二
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty心跳检测机制
查看>>
Netty核心模块组件
查看>>
Netty框架内的宝藏:ByteBuf
查看>>
Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
查看>>
Netty源码—2.Reactor线程模型一
查看>>
Netty源码—3.Reactor线程模型三
查看>>
Netty源码—4.客户端接入流程一
查看>>