背景

很多时候我们已经熟悉了框架的运用,但是有时候就是忘了怎么用

所以这里想记下大部分的框架使用方法,方便使用的时候拷贝

一、安装

npm 方式

npm install vuex --save

yarn 方式

yarn add vuex

二、vuex 用法

1、引入以及安装

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {}
})
new Vue({
// 把 store 提供给 store 选项,
// Vue 最初实例化的时候将 store 的实例注入到所有的子组件,意味着子组件可以使用 this.$store 调用 store 实例
store
})

2、正常使用

(1)、state

(2)、getters

(3)、mutations

(4)、actions

const store = new Vuex.Store({
state: {
count: 0,
todos: [
{ id: 1, done: true },
{ id: 2, done: false }
]
},
// 是 state 的 computed
getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
},
doneTodoCount: (state, getters) => {
return getters.doneTodos.length
}
},
// mutation 必须是同步函数,以便追踪状态(编写规范如此,非强制)
// 可以使用 state.obj = { ...state.obj, newProp: 1 } 进行值的替换(新对象替换旧对象,支持增加新属性)
mutations: {
mutationChangeState__increment(state, payload) {
// payload: 调用该方法时,传递进来的参数
state.count++
}
},
// mutation 里不允许的异步操作,可以放在 action 里面
actions: {
// 1、普通操作
actionCallMutation__mutationChangeState__increment(context) {
// context 是与 store 实例具有相同方法和属性的对象
context.commit('mutationChangeState__increment')
},
// 解构 context 使用
actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
commit('mutationChangeState__increment')
}, // 2、Promise 应用
// 异步操作转同步 Promise 1
actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
return new Promise((resolve, reject) => {
// ...
// resolve()
// reject()
})
},
// 异步操作转同步 Promise 2
actionCallMutation__mutationChangeState__increment2({ state, commit, dispatch, getters }) {
dispatch('actionCallMutation__mutationChangeState__increment').then(() => {
// ...
})
}, // 3、async/await 应用
// 异步操作转同步 async 1
async actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
await getData()
},
// 异步操作转同步 async 2
async actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
await dispatch('actionCallMutation__mutationChangeState__increment')
// dosomething...
},
}
})
export default store

3、存在子模块

3.1、modulesA

// 注意!注意!注意!
// modulesA 中的
// Astate,Agetters,Amutations,Aactions 应该为
// state,getters,mutations,actions
// 我这里是为了区分子模块和根模块才这么命名
const modulesA = {
// 1、在 namespaced 为 false 的情况下:
// 默认情况下,模块内部的 action、mutation、getter
// 分别和根模块的 action、mutation、getter 共享一个命名空间
// 即 Vuex 实例的 _getters、_mutations、_actions
// store: {
// _getters: {},
// _mutations: {},
// _actions: {}
// } // (1)、如果子模块的 getters 定义了和根模块相同的 getters,将会报错提示定义了相同的变量名
// store: {
// _getters: {
// getter1: 0,
// getter2: {},
// }
// } // (2)、如果子模块的 mutation 定义了和根模块相同的的 mutation,Vue 将该同名 mutation 转换成以该 mutation 名称为变量名的数组,并存储这两个 mutation 函数
// 先执行根模块的 mutation ,然后执行子模块的 mutation
// store: {
// _mutation: {
// mutationRepeatName: [function(){}, function(){}],
// otherMutation: function(){}
// }
// } // 2、在 namespaced 为 true 的情况下,不存在覆盖根模块的情况
// (1)、如果子模块的 getters 定义了和根模块相同的 getters,不会报错,会加入模块名作为变量名前缀
// store: {
// _getters: {
// a/getter1: 0,
// getter1: {},
// }
// } // (2)、如果子模块的 mutation 定义了和根模块相同的的 mutation,会加入模块名作为 mutation 名前缀
// store: {
// _mutation: {
// a/mutationRepeatName: function(){},
// mutationRepeatName: function(){}
// }
// } // 3、启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit
// 所以 namespaced 的改变,不影响模块代码
namespaced: false, // 子模块的 Astate 直接附加到根模块的 state
// 在根模块的 state 中, 以子模块名为 key,作为 state 的一个属性存在
// state: {
// a: { // 这里即子模块的 Astate // }
// }
Astate: {
count: 0,
todos: [
{ id: 1, done: true },
{ id: 2, done: false }
]
},
Agetters: {
AdoneTodos: (Astate, Agetters, rootState, rootGetters) => {
// rootState 为根模块的 state
// rootGetters 为根模块的 rootGetters
return Astate.todos.filter(todo => todo.done)
},
},
Amuattions: {
mutationChangeState__increment(Astate, payload) {
// payload: 调用该方法时,传递进来的参数
Astate.count++
}
},
Aactions: {
actionCallMutation__mutationChangeState__increment({ Astate, Acommit, Adispatch, Agetters, rootState, rootGetters }) {
// rootState 为根模块的 state
Acommit('mutationChangeState__increment') // 调用时,传递第三个参数{ root: true }, 可以访问根模块的 actions: someMutation
Acommit('someMutation', null, { root: true })
},
someRootAction: {
root: true, // 设置 root 属性为 true,可以将 someRootAction 注册在根模块
handler (namespacedContext, payload) { ... } // -> 'someRootAction'
}
}
}

3.2、使用子模块

const store = new Vuex.Store({
modules: {
a: modulesA
},
state: {},
// 是 state 的 computed
getters: {},
// mutation 必须是同步函数,以便追踪状态(编写规范如此,非强制)
// 可以使用 state.obj = { ...state.obj, newProp: 1 } 进行值的替换(新对象替换旧对象,支持增加新属性)
mutations: {},
// mutation 里不允许的异步操作,可以放在 action 里面
actions: {}
})
export default store

三、组件内常用操作

1、在组件中使用实例调用

// 调用 modulesA
// 1、调用 state
this.$store.state.a.todos
// 2、调用 getter
this.$store.getters.AdoneTodos // namespaced: false
this.$store.getters['a/AdoneTodos'] // namespaced: true
// 3、调用 mutation
this.$store.commit('AmutationChangeState__increment') // namespaced: false
this.$store.commit('a/AmutationChangeState__increment') // namespaced: true
// 4、调用 action
this.$store.dispatch('AmutationChangeState__increment') // namespaced: false
this.$store.dispatch('a/AmutationChangeState__increment') // namespaced: true // state
this.$store.state['属性key']
// getters
this.$store.getters['属性key']
// 调用 mutation
this.$store.commit('mutationChangeState__increment', payload)
this.$store.commit({ // 对象风格调用,整个对象都将作为 payload 传递给 mutation 方法
type: 'mutationChangeState__increment',
payload1: '',
payload2: ''
})
// 调用 action
this.$store.dispatch('actionCallMutation__mutationChangeState__increment')
this.$store.dispatch({ // 对象风格调用,整个对象都将作为 payload 传递给 dispatch 方法
type: 'actionCallMutation__mutationChangeState__increment',
payload1: '',
payload2: ''
})

2、在组件中使用辅助函数调用

// 辅助函数
import { mapState, mapGetters, mapMutations, mapActions, createNamespacedHelpers } from 'vuex'
// or
const { mapState, mapGetters, mapMutations, mapActions, createNamespacedHelpers } = createNamespacedHelpers('子命名空间')
export default {
created() {
// 使用
// state
console.log(this.stateName1, this.stateName2)
// getter
console.log(this.getterName1, this.getterName2) // mutation
this.mutationName1()
this.mutationName2()
// action
this.actionName1()
this.actionName2()
},
computed: {
// mapState
// 数组用法
...mapState(['stateName1', 'stateName2']),
// 对象用法
...mapState({
stateName3: state => state.stateName3,
stateName4_alias: state => state.stateName4,
stateName5_alias: 'stateName5', // 此处 'stateName5'(注意是字符串) 等于 state => state.stateName5
stateName6_resolve: state => { // 获取经过处理的值
return state.count + this.stateName1
}
}),
// 导出子模块数据
// 导出用法随 `数组/对象` 用法,只不过加入命名空间前缀
...mapState(['stateName1', 'stateName2', 'module/stateName2']),
...mapState({
stateName7_module: state => state.module.stateName7,
stateName8_module: state => state.module.stateName8
})
...mapState('some/nested/module', {
stateName9: state => state.stateName9,
stateName10: state => state.stateName10
})
...mapState('some/nested/module', [
'stateName9',
'stateName10'
]) // mapGetters
// 数组用法
...mapGetters(['getterName1', 'getterName2'])
// 对象用法
...mapGetters({
getterName3_alias: 'getterName3'
})
},
methods: {
// mapMutations
// 数组用法
...mapMutations(['mutationName1', 'mutationName2']),
// 对象用法
...mapMutations({
mutationName3_alias: 'mutationName3'
}), // mapActions
// 数组用法
...mapActions(['actionName1', 'actionName2']),
// 对象用法
...mapActions({
actionName3_alias: 'actionName3'
}),
// 导出子模块数据
// 导出用法随 `数组/对象` 用法,只不过加入命名空间前缀
...mapActions(['module/actionName3']),
...mapActions('some/nested/module', [
'actionName3'
]),
...mapActions('some/nested/module', {
actionName3_alias: 'actionName3'
}),
}
}

Vuex 常规用法的更多相关文章

  1. GridView的常规用法

    GridView控件在Asp.net中相当常用,以下是控件的解释,有些是常用的,有些是偶尔用到的,查找.使用.记录,仅此而已.(最后附带DropDownList控件) ASP.NET中GridView ...

  2. mapreduce的cleanUp和setUp的特殊用法(TopN问题)和常规用法

    一:特殊用法 我们上来不讲普通用法,普通用法放到最后.我们来谈一谈特殊用法,了解这一用法,让你的mapreduce编程能力提高一个档次,毫不夸张!!!扯淡了,让我们进入正题: 我们知道reduce和m ...

  3. 【python】-matplotlib.pylab常规用法

    目的: 了解matplotlib.pylab常规用法 示例 import matplotlib.pylab as pl x = range(10) y = [i * i for i in x] pl. ...

  4. MarkDown的常规用法

    MarkDown的常规用法 标题 # 一级标题 ## 二级标题 ... ###### 六级标题 列表 第二级 - 和 空格 + 和 空额 * 和 空格 第三级 代码块 多行代码块 3个` 回车 单行代 ...

  5. vue vuex的用法

    1.引入  vue.js    vuex.js 文件 2.创建Store文件 var sSatte=new Vuex.Store({ state:{}, mutations:{}, actions:{ ...

  6. vuex 基本用法、兄弟组件通信,参数传递

    vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值,需要先将值传给父组件,再传给子组件,异常麻烦. vuex大概思路:a=new Vue(),发射数据'msg':a.$emit ...

  7. C# 当中 LINQ 的常规用法(Lambda 方式)

    仅以本篇博文记录 LINQ 相关操作的基本知识,原型参考自 MSDN 相关知识,中间加以自己的理解与 DEMO. 1. IEnuemrable<T>.Select() Select 方法比 ...

  8. iOS -Swift 3.0 -String(字符串常规用法)

    // // ViewController.swift // Swift-String // // Created by luorende on 16/9/10. // Copyright © 2016 ...

  9. 关于strong、copy、weak、assign的常规用法

    strong   对于普通的OC对象都是使用strong copy     对于 NSString,Block weak    用于OC对象,1.当出现循环强引用的时候,必须要保证一端是weak, 2 ...

随机推荐

  1. 【InnoDB】体系结构

    一.概述: innodb的整个体系架构就是由多个内存块组成的缓冲池及多个后台线程构成.缓冲池缓存磁盘数据(解决cpu速度和磁盘速度的严重不匹配问题),后台进程保证缓存池和磁盘数据的一致性(读取.刷新) ...

  2. hdu 1540 Tunnel Warfare (线段树,维护当前最大连续区间)

    Description During the War of Resistance Against Japan, tunnel warfare was carried out extensively i ...

  3. Linux下Mysql安装与常见问题解决方案

    1.Mysql安装 环境: Mysql版本: 开始安装: 首先检查环境有没有老版本mysql,有的话先卸载干净,具体百度. 接着先获取mysql的安装包:wget https://dev.mysql. ...

  4. PHP基础知识总结(五) php面试题

    1.Ajax跨域 json:数据交换格式,{"name":"wangtianle"} jsonp:非官方跨域数据交换协议,可以通过动态添加<script/ ...

  5. 2019ccpc秦皇岛/Gym102361 F Forest Program 仙人掌上dfs

    题意: 某地沙漠化严重,沙漠里长了很多仙人掌,现在要让你删掉仙人掌的一些边让它的所有连通分量都是树,就完成了沙漠绿化(什么鬼逻辑?)让你计算删边的方案数. 仙人掌是一种特殊的图,它的每一条边只属于1或 ...

  6. ICO和区块链区别

    区块链项目众筹(ICO)浅析 2017-07-25 原创 Fintech科普大使 ICO是区块链初创公司项目融资的重要方式类似于Kickstarter众筹,但有不同之处(具体在下一节详述),可以避开传 ...

  7. 修改PhpStorm创建Php类文件时头部作者

    原文链接:https://segmentfault.com/a/1190000015617093 首先打开phpstorm后找到Setting/Editor/Inspections/PHP/File ...

  8. flask编程规范

    参考:http://dormousehole.readthedocs.org/en/latest/styleguide.html   Flask遵循的是Pocoo的编程规范,Pocoo遵守PEP8的规 ...

  9. 大数据和AI怎么与现代教育相结合?

    大数据和AI怎么与现代教育相结合? 比尔·盖茨曾预言,"5年以后,你将可以在网上免费获取世界上最好的课程,而且这些课程比任何一个单独大学提供的课程都要好." 现在看来,虽然并不是每 ...

  10. centos为用户添加sudo功能

    su chmod a+w /etc/sudoers vim /etc/sudoers [找到root ALL=(ALL) ALL这行] 复制出新的一行,并且将root改为daniel(当前用户名) c ...