【Vue】状态管理
快速入门
1. 安装vuex库
- cnpm install -S vuex
2. 创建Vuex.Store
- import Vue from 'vue'
- import Vuex from 'vuex'
- Vue.use(Vuex);
- const store = new Vuex.Store({
- //组件数据源,单一的state属性
- state: {
- clickCount: 0
- },
- //相当于属性,封装获取state
- getters: {
- getClickCount: state => {
- return state.clickCount;
- }
- },
- //封装引起状态变化的方法
- mutations: {
- increment(state) {
- state.clickCount++;
- }
- },
- //类似于 mutation,不同在于actions支持异步,不是直接变更状态,而是提交到mutation
- actions: {
- increment(context) {
- context.commit('increment')
- },
- async incrementAsync({ commit }) {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- try {
- commit('increment');
- resolve(new Date().getTime() + ' 成功执行');
- } catch (e) {
- reject(e);
- }
- }, 1000)
- });
- }
- }
- });
- export default store;
3. Vue实例加入store
- new Vue({
- router: router,
- store: store,
- render: h => h(App),
- }).$mount('#app')
4. 组件获取store值
- <script>
- import { mapGetters } from "vuex";
- export default {
- computed: mapGetters({ count: ["getClickCount"] }),
- };
- </script>
5. 组件触发更新
- <script>
- export default {
- data() {
- return { times: 0 };
- },
- methods: {
- increment() {
- this.times++;
- //分发到action
- this.$store.dispatch("incrementAsync");
- //提交到mutations
- this.$store.commit("increment");
- },
- },
- };
- </script>
解析
Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
State - 数据源
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。
Vue通过store选项,调用Vue.use(Vuex)注入到每一个子组件中(类似路由)
组件获取State
- computed: {
- count () {
- return this.$store.state.count
- }
- }
或者使用辅助函数mapState
- computed: mapState({
- // 箭头函数可使代码更简练
- count: state => state.count
- })
Getter - 数据封装读取(类似属性)
Getter 接受 state 作为其第一个参数
- getters: {
- doneTodos: state => {
- return state.todos.filter(todo => todo.done)
- },
- getTodoById: (state) => (id) => {
- return state.todos.find(todo => todo.id === id)
- }
- }
通过属性访问
- store.getters.doneTodos
通过方法访问
- store.getters.getTodoById(2)
Getters 也提供了一个辅助函数方便访问(mapGetters )
Mutation - 进行状态更改的地方
定义Mutation
- mutations: {
- increment (state, n) {
- state.count += n
- }
- }
组件触发变更
- store.commit('increment', 1)
Mutations也提供辅助函数(mapMutations)
- import { mapMutations } from 'vuex'
- export default {
- // ...
- methods: {
- ...mapMutations([
- 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
- // `mapMutations` 也支持载荷:
- 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
- ]),
- ...mapMutations({
- add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
- })
- }
- }
注意事项
- Mutation 必须是同步函数
- 最好提前在你的 store 中初始化好所有所需属性。
- 需要在对象上添加新属性时使用 Vue.set 或 替换旧对象
Action - 对Mutation封装
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
定义Action
- actions: {
- increment ({ commit }) {
- commit('increment')
- }
- }
组件分发Action
- store.dispatch('increment')
支持异步方式分发
- actions: {
- async incrementAsync({ commit }) {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- try {
- commit('increment');
- resolve(new Date().getTime() + ' 成功执行');
- } catch (e) {
- reject(e);
- }
- }, 1000)
- });
- }
- }
组件调用异步分发
- this.$store.dispatch("incrementAsync").then(
- (data) => {
- console.log(data);
- },
- (err) => {
- console.log(err);
- }
- );
参考文章
转发请标明出处:https://www.cnblogs.com/WilsonPan/p/12773090.html
【Vue】状态管理的更多相关文章
- Vue状态管理vuex
前面的话 由于多个状态分散的跨越在许多组件和交互间各个角落,大型应用复杂度也经常逐渐增长.为了解决这个问题,Vue提供了vuex.本文将详细介绍Vue状态管理vuex 引入 当访问数据对象时,一个 V ...
- vue状态管理器(用户登录简单应用)
技术点:通过vue状态管理器,对已经登录的用户显示不同的页面: 一 vue之状态管理器应用 主要用来存储cookie信息 与vue-cookies一起使用 安装:npm install vue-co ...
- vuex(vue状态管理)
vuex(vue状态管理) 1.先安装vuex npm install vuex --save 2.在项目的src目录下创建store目录,并且新建index.js文件,然后创建vuex实例,引入 ...
- Vue状态管理之Vuex
Vuex是专为Vue.js设计的状态管理模式.采用集中存储组件状态它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 1.首先让我们从一个vue的计数应用开始 ...
- Vue状态管理
1.导出Vuex import Vuex from 'vuex' 2.定义store /*状态管理*/ const store = new Vuex.Store({ state: { headerSh ...
- vue - 状态管理器 Vuex
状态管理 vuex是一个专门为vue.js设计的集中式状态管理架构.状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态.简单的说就是data中需要共用的属性.
- 五、vue状态管理模式vuex
一.vuex介绍 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 即data中属性同时有一 ...
- Vue 状态管理
类flux状态管理的官方实现 由于多个状态分散的跨越在许多组件和交互间的各个角落,大型应用复杂度也经常逐渐增长. 为了解决这个问题,vue提供了vuex:我们有收到elm启发的状态管理库,vuex甚至 ...
- vuex vue状态管理
第一步安装vuex(安装在生产环境) npm install vuex 第二步 src下新建store文件夹 用来专门放状态管理,store文件夹下新建四个js文件 index.js actions ...
- Vue状态管理之Bus
一般在项目中,状态管理都是使用Vue官方提供的Vuex 当在多组件之间共享状态变得复杂时,使用Vuex,此外也可以使用Bus来进行简单的状态管理 1.1 父组件与子组件之间的通信 vue.config ...
随机推荐
- OpenCV-Python 形态学转换 | 十七
目标 在这一章当中, 我们将学习不同的形态学操作,例如侵蚀,膨胀,开运算,闭运算等. 我们将看到不同的功能,例如:cv.erode(),cv.dilate(), cv.morphologyEx()等. ...
- 模型压缩一半,精度几乎无损,TensorFlow推出半精度浮点量化工具包,还有在线Demo...
近日,TensorFlow模型优化工具包又添一员大将,训练后的半精度浮点量化(float16 quantization)工具. 有了它,就能在几乎不损失模型精度的情况下,将模型压缩至一半大小,还能改善 ...
- 使用FME裁剪矢量shapefile文件
- Arcgis中制作热力图
摘要 使用核函数根据点或折线 (polyline) 要素计算每单位面积的量值以将各个点或折线 (polyline) 拟合为光滑锥状表面. 插图
- __str_方法和__repr__的区别
__str__方法和__repr__方法: 官方文档解释: Object.__repr__(self): 由 repr() 内置函数调用以输出一个对象的“官方”字符串表示.如果可能,这应类似一个有效的 ...
- [Asp.Net Core] 为什么选择 Blazor Server Side (一) 快速实现图片验证码
关于Blazor 由于在国内, Blazor一点都不普及, 建议读者翻看我之前写的随笔, 了解Blazor Server Side的特点. 在一段时间内, 我会写一些解说分析型的 "为什么选 ...
- Reface.NPI 方法名称解析规则详解
在上次的文章中简单介绍了 Reface.NPI 中的功能. 本期,将对这方法名称解析规则进行详细的解释和说明, 以便开发者可以完整的使用 Reface.NPI 中的各种功能. 基本规则 方法名称以 I ...
- [原创] 关于步科eview人机界面HMI的使用 - HMI做Slave - Modbus RS485通讯
做测试设备,或者自动化设备常常用到HMI 触摸屏 我有个案子用到了 步科的eview 触摸屏 型号 ET070 我的是单片机主板 控制 HMI显示,通讯用485 MODBUS 单片机板充当 主控 , ...
- JQ前端上传图片显示在页面以及发送到后端服务器
// 单张上传照片 html: <div class="azwoo"></div> <div class="azwot"& ...
- Html 慕课园编程练习10-1
23:10:25 2019-08-14 自己写的这个好丑.... 题目:利用之前我们学过的JavaScript知识,实现选项卡切换的效果. 效果图: (另外 这个动图是怎么插入的 用url就行 复制就 ...