公司数据平台现在的规模已经有点大了,考虑到以后,可能会出现数据共享的问题,所以我先粗略了解一下vuex以备不时之需。
首先安装vuex
1 2
| npm install vuex --save
|
src目录下新建vuex目录
vuex文件夹下新建store.js
先在store.js中写入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
const state = { count: 10 }
const mutations = { add(state,n) { state.count += n }, reduce(state,n) { state.count -= n } }
const getters = { count: state => { return console.log(state.count) } }
const actions = { addAction({ commit }) { commit('add',1) }, reduceAction({ commit }) { commit('reduce') } }
export default new Vuex.Store({ state, mutations, getters, actions })
|
组件中使用
1 2 3 4 5 6 7
| <tempate> <div> {{ count }} <button @click="add(10)">-</button> <button @click="reduce(10)">+</button> </div> </template>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import store from '../vuex/store'
import { mapState,mapMutations,mapGetters,mapActions } from 'vuex' export default { store, computed: { ...mapState(['count']), ...mapGetters(['count']) }, methods:{ ...mapMutations(['add','reduce']), ...mapActions(['addAction','reduceAction']) } }
|