vuex详细教程

在Vue组件使用Vuex

state

注入机制

import store from './store/store.js';

就可以在组件使用this.$store来调用方法

// Counter 组件
const Counter = {
    template: `<div>{{ count }}</div>`,
    computed: {
        count () {
            return this.$store.state.count
        }
    }
}

mapState函数

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

getters

组件使用

this.$store使用
const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})
computed: {
  doneTodos () {
    return this.$store.getters.doneTodos
  }
}
mapGetters辅助函数

与mapState类似,都能达到简化代码的效果。mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性:
import { mapGetters } from ‘vuex’

export default {
  // ...
  computed: {
    // 使用对象展开运算符将 getters 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

上面也可以写作:

computed: mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])

所以在Vue的computed计算属性中会存在两种辅助函数:

import { mapState, mapGetters } form 'vuex';

export default {
    // ...
    computed: {
        mapState({ ... }),
        mapGetter({ ... })
    }
}

Mutations

之前也说过了,更改Vuex的store中的状态的唯一方法就是mutations。
每一个mutation都有一个事件类型type和一个回调函数handler。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

调用mutation,需要通过store.commit方法调用mutation type:

store.commit('increment')

Payload 提交载荷

也可以向store.commit传入第二参数,也就是mutation的payload:

mutaion: {
    increment (state, n) {
        state.count += n;
    }
}

store.commit('increment', 10);

单单传入一个n,可能并不能满足我们的业务需要,这时候我们可以选择传入一个payload对象:

mutation: {
    increment (state, payload) {
        state.totalPrice += payload.price + payload.count;
    }
}

store.commit({
    type: 'increment',
    price: 10,
    count: 8
})

mapMutations函数

不例外,mutations也有映射函数mapMutations,帮助我们简化代码,使用mapMutations辅助函数将组件中的methods映射为store.commit调用。

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment' // 映射 this.increment() 为 this.$store.commit('increment')
    ]),
    ...mapMutations({
      add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
    })
  }
}

注 Mutations必须是同步函数。

如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了。

Actions

在组件中分发 Action
你在组件中使用 this.$store.dispatch(‘xxx’) 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')
<template>
    <div>
        <p>{{count}}</p>
        <p>{{city}}</p>
        <button @click="backFn(1)">点我城市</button>
        home组件
    </div>
</template>
<script>
import {mapState} from 'vuex'
import {mapMutations} from 'vuex'
export default {
    computed: {
        ...mapState(['count']),
        city: function() {
            return this.$store.getters.getCityFn;
        },
        
    },
    methods: {
       backFn: function(cityname) {
           this.$store.dispatch("setCityName",cityname)
       }
    }
    
}
</script>
<style scoped>

</style>

定义

 // actions 注册并触发处理函数,可以传参,当这个函数被触发时,将状态提交到mutations中处理, 正在处理状态
     actions: {
        increment: ({commit}) => commit('increment'),  //在actions中一般做数据请求,再使用commit方法,这里直接赋值写死
      decrement: ({commit}) => commit('decrement'),
      setCityName({commit,state},name) {
          commit("setCity",name)
      }

    }
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

参考文档
Vuex官方文档
Vuex,从入门到入门
Vuex 通俗版教程
vuex的简单使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RDSunday

爱,就供养;喜欢/受益,就打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值