vuex
1.安装
npm install vuex --save
2.导入
import Vuex from 'vuex'
Vue.use(Vuex)
3.创建库
var store = new Vuex.Store({
state:{
count:0
},
mutations:{
increment(state){
state.count++;
},
remove(state,obj) {
state.count -= (obj.a + obj.b)
}
},
getters: {
optCount:(state => {
return '当前值:'+ state.count;
})
}
})
4.挂载
var vm = new Vue({
el:'#app',
render:function (c) {
return c(app)
},
router,
store
})
5.使用
<template>
<div>
<input type="button" value="减少" @click="remove">
<input type="button" value="增加" @click="add">
<br>
<input type="text" v-model="$store.state.count">
<h3>{{$store.getters.optCount}}</h3>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
add(){
this.$store.commit('increment')
},
remove(){
this.$store.commit('remove',{a:1,b:2})
}
}
};
</script>
<style scoped>
</style>
new Vuex.Store() 实例,得到一个 数据仓储对象
var store = new Vuex.Store({
state: {
// 大家可以把 state 想象成 组件中的 data ,专门用来存储数据的
// 如果在 组件中,想要访问,store 中的数据,只能通过 this.KaTeX parse error: Expected 'EOF', got '}' at position 36: … count: 0 }̲, mutations: …store.commit(‘方法名’)
// 这种 调用 mutations 方法的格式,和 this.$emit(‘父组件中方法名’)
subtract(state, obj) {
// 注意: mutations 的 函数参数列表中,最多支持两个参数,其中,参数1: 是 state 状态; 参数2: 通过 commit 提交过来的参数;
console.log(obj)
state.count -= (obj.c + obj.d)
}
},
getters: {
// 注意:这里的 getters, 只负责 对外提供数据,不负责 修改数据,如果想要修改 state 中的数据,请 去找 mutations
optCount: function (state) {
return ‘当前最新的count值是:’ + state.count
}
// 经过咱们回顾对比,发现 getters 中的方法, 和组件中的过滤器比较类似,因为 过滤器和 getters 都没有修改原数据, 都是把原数据做了一层包装,提供给了 调用者;
// 其次, getters 也和 computed 比较像, 只要 state 中的数据发生变化了,那么,如果 getters 正好也引用了这个数据,那么 就会立即触发 getters 的重新求值;
}
})
总结:
- state中的数据,不能直接修改,如果想要修改,必须通过 mutations
- 如果组件想要直接 从 state 上获取数据: 需要 this.$store.state.****
- 如果 组件,想要修改数据,必须使用 mutations 提供的方法,需要通过 this.$store.commit(‘方法的名称’, 唯一的一个参数)
- 如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters.