stare
state提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储
// 创建store数据源,提供唯一公共数据(vuex中写) const store = new Vuex.Store({ state: { count: 0 } // state中的count(数据)就是共享的数据 })
组件访问 State 中数据的第一种方式:
this.$store.state.全局数据名称 (组件,html中写)
(在template中this可以省略,也就是在html中this可以省略)
<div>公共数据count:{{$store.state.count}}</div>
组件访问 State 中数据的第二种方式(组件,html中写):
// 1. 从 vuex 中按需导入 mapState 函数
import { mapState } from ‘vuex‘
// 2. 通过刚才导入的 mapState 函数,将当前组件需要的全局数据(vuex中的数据),映射为当前组件的 computed 计算属性:
computed:{...mapState([‘count‘])}
// 3.可以在HTML中直接用count来使用state中的count数据
<div>公共数据count:{{count}}</div>
Mutation
Mutation 用于变更 Store中 的数据。
① 只能 通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
② 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
③ 不允许在组件中通过$store.state直接修改 state 中的数据(因为后期无法快速找到 是谁 修改的数据,但使用mutation可以在vuex中快速找到,方便后期的维护)
// 定义 Mutation(vuex中写)
const store = new Vuex.Store({ state: { count: 0 }, mutations: { add(state) { // state就是上面的state函数(第一个形参永远都是自身的state,state代表当前全局的数据对象) // 变更状态 state.count++ } } })
// 触发mutation的第一种方式(组件,html中写)
methods: { handle1( ) { // 触发 mutations 的第一种方式 commit的作用就是调用 某个 mutation 的函数 this.$store.commit(‘add‘) } }
触发mutation并传递参数
// 定义Mutation(vuex中写)
const store = new Vuex.Store({ state: { count: 0 }, mutations: { addN(state, step) { // 第一个形参永远是state,第二个 参数是外界传递过来的值 // 变更状态 state.count += step } } })
// 触发mutation (组件,html中写)
methods: { handle2( ) { // 在调用 commit 函数, 触发 mutations 时携带参数 this.$store.commit(‘addN‘, 3) // 通过commit调用mutations,同时携带参数 3 ,第二个参数对应着mutation中的第二个参数 } }
this.$store.commit( ) 是触发 mutations 的第一种方式,触发 mutations 的第二种方式:(组件,html中写)
// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from ‘vuex‘
// 2. 通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:
methods: { ...mapMutations([‘add‘,‘addN‘])}
// 3.就可以直接用 this.add( )来调用 mutation中的 add 函数
// 4.传参就变成了this.add(3) 3就是mutation的第二个参数
原文:https://www.cnblogs.com/xhxdd/p/12848385.html