vuex的使用
vuex其实可以看成一个公共的数据仓库,从作用来说大致上可以看成是我们的cookie或者localStorage,下面我们来看看怎么使用吧
1.安装
vuex不是vue内置的所以需要额外安装
npm i vuex --save
2.设置仓库
在src下面新建一个文件夹,这里我新建一个store/index.js,内容大致为:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 0 } const mutations = { add (state, n) { state.count += n }, reduce (state, n) { state.count -= n } } const getters = { count2 (state) { return state.count + 100 } } const actions = { aAdd (context) { context.commit('add', 6) } } export default new Vuex.Store({ state, mutations, getters, actions })
3.引入使用
vuex实例可以被引入到Vue实例和Vue组件中,引入后可以在this.$store中使用vuex
<template>
<div>
<!-- 通过$store.state获取仓库数据 -->
count:{{$store.state.count}}<br>
<!-- 通过computed mapState来简化数据写法 -->
count:{{count}}<br>
count2:{{count2}}
<!-- 通过$store.commit来触发仓库方法 -->
<button @click="$store.commit('add', 10)">+</button>
<!-- 通过methods mapMutation 来简化调用仓库方法 -->
<button @click="reduce(2)">-</button><br>
actions调用mutions的方法<button @click="aAdd">加</button>
</div>
</template>
<script>
import store from '@/store'
import { mapState, mapMutations, mapGetters, mapActions } from 'vuex'
export default {
data () {
return {}
},
// 通过mapMutation来简化vuex数据获取
methods: {
...mapMutations(['add', 'reduce']),
// 用传对象的形式可以更加灵活
//...mapMutations({
// count: state => state.count,
// countAlias: 'count',
// })
...mapActions(['aAdd'])
},
store,
// 通过mapState来简化vuex数据获取
computed: {
...mapState(['count']),
...mapGetters(['count2'])
// count2 () {
// return this.$store.getters.count2
// }
}
// computed: mapState({
// count: state => state.count
// })
// computed: {
// count () {
// return this.$store.state.count
// }
// }
}
</script>
ps:map系列的方法既可以传入数组,也可以传入对象的形式
vuex主要内容包括:state(相当于data)、mutations(相当于methods)、getter(相当于computed)、actions(这个是调用mutation用的)、modules(大型应用使用,这里不演示了)

浙公网安备 33010602011771号