vueX的使用

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

    









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值