vuex是针对于vue开发的状态管理模式。采用的是集中式存储管理应用的所有组件的状态,并以响应的规则保证状态以一种可预测的方式发生变化。它也是类似于Flux,Redux和The Elm Architecture
Vuex和单纯的全局对象有两个不同点:
1、Vuex的状态存储是响应式的。
2、不能直接改变store中的状态。
- 安装
npm install vuex
或
yarn add vuex
- 使用
// 创建store文件
// 在mian.js中
import Vue from 'vue'
import Vuex from 'vuex'
import store from './store'
Vue.use(Vuex)
new Vue({
store,
render: h => h(App),
}).$mount('#app')
核心的概念
State
主要是存储默认的全局的数据,通过store选项,提供了一种机制将状态从根部组件“注入”到每个子组件中。
- 在store.js文件中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0
}
})
- 在组件中引用
<template>
<div>
第一种方法
<span>{{this.$store.state.count}}</span>
第二种方法
<span>{{count}}</span>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'Users',
data() {
return {
// count: this.$store.state.count
}
},
compunted:{
// 将全局数据,映射为当前组件的计算属性,mapState辅助函数帮助我们生成计算属性
...mapState(['count'])
}
}
</script>
Mutations
主要是修改state中的数据,虽然可以直接在子组件的methods中直接修改,但是是不合法的,所以要在全局的mutations中修改
- store.js
// state是全局的state
add(state) {
state.count++
},
// step 是组件传过来的参数
addN(state,step){
state.count +=step
}
- 子组件
methods:{
handle() {
// 触发mutations的第一种方式
// 触发mutations时携带参数
this.$store.commit('add')
},
}
或
<template>
<div>{{count}}</div>
<button @click="add">+1</button>
<!--传入参数-->
<button @click="addN(3)">+N</button>
</template>
methods:{
...mapMutations(['add','addN'])
// 也可以使用
handle(){
this.$store.commit('add')
//this.$store.commit('addN',3)
}
}
Action
Action类似于mutation,不同在于
-
Action提交的是mutation,而不是直接变更状态
-
Action可以保函任意异步操作
-
store.js
addNasync(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
}
- 子组件
this.$store.dispatch('addNasync', 5)
// 当然也可以利用
...mapActions(['addNasync'])
Getter
就是从store中的state中派生出一些状态,也就是对state中的数据进行加工处理,同时不会改变原来的state的值
-store.js
getters: {
showNum: store => {
return '当前最新的数量是【' + store.count + '】'
}
}
- 子组件
//通过属性访问
this.$store.getters.showNum
或
通过辅助函数
...mapGetters(['showNum'])
在上面常用的辅助函数
mapState
,mapMutations
,mapActions
,mapGetters