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>
本文详细介绍了如何在Vue项目中使用Vuex进行状态管理。包括创建store文件夹及index.js入口文件,定义模块如购物车模块,以及在main.js中引入store。此外还展示了如何在组件中通过mapState、mapGetters和mapActions来调用store中的状态、getter和action。
1089

被折叠的 条评论
为什么被折叠?



