1../src/store 新建store文件夹 ,store文件夹下
index.js 入口文件:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); //导入你需要的模块 import cart from './modules/cart.js' export default new Vuex.Store({ modules: { cart }, })
./src/store/modules文件夹
存放各个模块,模块里面内容:
const state={ count: 0 } //computed const getters={ countAdd () { //return this.$store.state.count+2 } } //methods const actions={ increment ({commit, state}) { console.log('action 的位置',state.count) commit('increment') } } const mutations={ increment (state) { state.count++ } } export default { namespaced: true, state, getters, actions, mutations }
2.在main.js里面
import store from './store'
new Vue({ el: '#app', store, router, render: h => h(App) })
3.在其他组件中调用:
<script> import store from '../store' import {mapState, mapGetters, mapActions} from 'vuex' export default { computed: { ...mapState('cart', [ //映射 'count' ]), ...mapGetters('cart', [ 'countAdd' ]), }, methods: { ...mapActions('cart',[ 'increment', ]) } } </script>