state
单一状态树, 意思是一个对象包含了全部应用层级状态, Store 将作为唯一数据源.
每个应用, 仅仅有且只有一个 store 实例!
mapState
当一个组件组件组件需要多个状态值时, 可以调用 mapState 函数赋值给 computed 返回是对象.
- // mapState 基本用法, 3 种: 箭头函数, 字符串, 函数.
- computed:mapState({
- //1, 箭头函数 countFromStore:state=>state.count
- //2, 字符串 countFromStore: 'count'等价于 state=>state.count
- //3, 函数需要使用组件内数据访问 this 时, 还可以用函数
- countFromStore(state) {
- return state.count+this.localCount;
- }
- }),
- // 如果同名取 Store 中的值, 可以取 count 字符串放在数组中传递给 mapState.
- computed:mapState([
- 'count'// 可以访问多个状态
- ]),
- // mapState 返回对象所以可以扩展 computed 对象.
- computed: {
- ...mapState([
- 'count'
- ]),
- localCount() {
- return this.localCount + this.$store.state.count;
- }
- }
- getters
可以吧 getters 当作是 state store 的计算属性, 传参是 state .
- vue.use(Vuex);
- conststore=newVuex.Store({
- state:{
- count:1,
- name:'NewStation',
- todos:[
- {
- id:1,text:'todos -1',done:true
- },
- {
- id:2,text:'todos -2',done:false
- },
- ]
- },
- mutations:{
- //this.$store.commit('changeName') 触发 commit 更新 store
- increment(state) {
- state.count++
- },
- changeName(state) {
- state.name='NewPlace'
- }
- },
- getters:{
- //this.$store.getters.doneTodos 获取 getters 编译后的值
- doneTodos:state=>{
- returnstate.todos.filter(todo=>todo.done)[0].done;
- },
- doneState:(state, getter)=>{
- returngetter.doneTodos+ 'getter 作为其他 getter 的传参';
- }
- }
- });
- mapGetters
辅助函数,, 支持 2 种方式转换, 把 store 中的 getters 可以支持传参, 映射到局部计算属性.
computed:{
...mapGetters([ 数组
- 'doneTodos', // 可以直接调用
- ]),
...mapGetters({ 对象
- aliasFillname:'getFillName'// 给 getter 加别名.
- }),
- }
- Mutation
更新 store 状态 的唯一方法是提交 mutation. Vuex 中的 mutation 类似于事件: 每个 mutation 都有自己的事件类型和回调函数, 这个回调函数就是我们状态更改的地方, 并接受 state 作为第一个参数.
- const store = new Vuex.Store({
- state: {
- count: 1
- },
- mutations: {
- increment(state) {
- // 变更状态
- state.count++
- }
- }
- })
store.commit('increment') 只能用这个方式修改状态!
触发 mutation 更新状态, 触发一个叫 increment 类型的事件, 并回调执行 这个类型的注册函数.
提交负载 Payload
可以给 commit 传参, 称为 Payload 负载, 通常是一个对象.
this.$store.commit('increment', { account: 'local' })
对象的风格提交
只给 mutation 传递对象, 表示整个对象被当做 Payload, 被解析, mutation 中获取的方式是不变的.
- this.$store.commit({
- type: 'increment',
- account: 'local'
- })
Mutation 需遵守 vue 响应规则
1, 提前在 store 中初始化所有有声明的属性值
2, 获取对象值之后, 如需修改推荐调用 Vue.set (obj, 'newkey', 'newvalue') 或者 这样 {...obj, newProp: 123}
store 的对象放在前.
3, 推荐使用常量 const 方式命名 mutation 中事件的类型名, 也可以不用.
Mutation 必须是同步函数
Store 对生命周期的影响
初始阶段
就是组件实例化和 mounted 的过程, 和从 data 或 props 中取值并没有区别.
- App ---beforeCreate--
- App ---created---
- App ---beforeMount---
- Helloworld ---beforeCreate--
- Helloworld ---created---
- Helloworld ---beforeMount---
- Helloworld ---mounted---
- App ---mounted---
store 的 state 更新阶段
- App ---beforeUpdate---
- Helloworld ---beforeUpdate---
- Helloworld ---updated---
- App ---updated---
来源: http://www.bubuko.com/infodetail-3165082.html