拾光°
vuex是专门用来管理vue.js应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在一起,
集中式来管理。需要声明的是,这里所说的状态指的是vue组件中data里面的属性。
简单的来说,它就是存储公共变量的东西,然后插件可以通过它来访问,或者修改数据,来达到响应式.相当于一个仓库,里面可以放很多公共的东西,而这些公共的东西都可以让组件使用.
vuex中核心模块有:
State
Mutation
Action
Getter
State提供唯一的公共数据源, 所有共享的数据都要统一放到Store的State中进行存储。类似于data函数
管理数据,管理的数据是响应式的,当数据改变时驱动视图更新。
<!-- this.$store.state.全局数据名称 -->
<template>
<div>
<h3>当前最新的count值为: {{$store.state.count}}</h3>
</div>
</template>在template中访问vue实例中的内容时,this可以省略
完整写法:{{this.$store.state.count}}
// 1、从vuex 中按需引入 mapState
import { mapState } from 'vuex'
// 2、将全局数据,映射为当前组件的计算属性
computed:{
...mapSate(['count'])
}
Mutation用于变更Store中的数据。更新数据,state中的数据只能使用mutations去改变数据。
①只能通过mutation变更Store数据,不可以直接操作Store中的数据。
②通过这种方式虽然操作起来稍微繁琐-些,但是可以集中监控所有数据的变化。
为啥只能通过mutation来操作store的数据呢?
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state: {
count: 0
},
mutations: {
// 第一个默认就是state 第二个参数(step)就是携带的参数
add(state, step) {
state.count++
},
actions: {}
}
})
<script>
export default {
data() {
return {}
},
methods: {
btnHandler1() {
this.$store.commit('add')
},
btnHandler2() {
// commit 的作用,就是调用某个mutation 函数
this.$store.commit('addN ', 3)
},
},
}
</script>// 1.从vuex 中按需导入mapMutations 函数
import { mapMutations } from 'vuex'// 2.将指定的 mutations 函数,映射为当前组件的methods函数
methods:{
...mapMutations (['add', ' addN' ])
}
Action用于处理异步任务。
请求数据,响应成功后把数据提交给mutations
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。
<script>
export default {
data() {
return {}
},
methods: {
btnHandler1() {
this.$store.commit('add')
},
btnHandler2() {
// commit 的作用,就是调用某个mutation 函数
this.$store.commit('addN ', 3)
},
},
addAsync(context) {
setTimeout(() => {
// 在actions 中,不能直接修改state 中的数据;
//必须通过context.commit() 触发某个mutation才行
context.commit('add')
}, 1000)
},
}
</script> //直接全局调用
this.$store.dispatch('addNAsync', 5)//1.从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'
// 2.将指定的actions 函数,映射为当前组件的methods 函数
methods: {
mapActions(['addASync','addNASync' ])
}
Getter用于对Store中的数据进行加工处理形成新的数据。
//定义Getter :
const store = new Vuex.store({
state: {
count: 0
},
getters: {
showNum: state => {
return '当前最新的数量是[' + state.count + ']'
}
}
})
{{ this.$store.getters.名称 }}
// 先按需引入
import {
mapGetters
} from 'vuex';
computed: {
...mapGetters(['showNum'])
}