学习vuex

本文详细介绍了如何在Vue应用中安装和配置Vuex,包括创建store.js文件,定义state、mutations、actions和getters,以及在main.js中全局注册store并进行操作。还讨论了Vuex的扩展使用方法——mapState、mapMutations、mapActions和mapGetters。
摘要由CSDN通过智能技术生成

第一步骤  安装vuex,创建一个store.js文件

        这个里文件里面包括有这几部分常用的

       state===>类似data

       mutations(同步操作) ===》类似methods

       actions(异步操作)

       getters===》类似计算

例子

store.js代码如下

import {createStore} from 'vuex'  //引入vuex里面的createStore来创建一个实例化对象

 const store = createStore({     //把创建的一个实例化对象赋值给store,方便暴露出去,看store.js文件最下面一行代码

    state:{

        count:0,   //声明的一个变量count,有点类似全局变量

    },

    mutations:{

       //把经常用到的方法放到这里,别处想用就使用.commit()来调取,如

       //无参  别处想用就使用.commin('increment')来调取

        increment(state){

            // 不能再mutations进行异步操作,要借助action对象才可以

            state.count++

        },

      //有参  别处想用就使用.commin('incrementN',3)来调取

        incrementN(state,step){

            state.count+=step

        },

    },

    actions:{

       //把经常用到的异步方法放到这里,别处想用就使用.dispatch()来调取,如

       //无参  别处想用就使用dispatch('addAsync')来调取

        addAsync(context){     // context就是store实例对象

            console.log("2222",context);  //打印出来的数据如图1

            setTimeout(()=>{

                // commit的作用,就是调用某个mutation函数

                context.commit('increment')

            },1000)

        },

     //有参  别处想用就使用.dispatch('addAsyncN',3)来调取

        addAsyncN(context,step){

            setTimeout(()=>{

                context.commit('incrementN',step)

            },1000)

        },

    },

    getters:{

       //别处使用.getters.showNum

        showNum(state){

            return '当前最新的数量是['+ state.count +']'

        }

    }

})

export default store

             图一

第二步:在mian.js文件里面写

// 引入大型store

import store from './store.js'

//vue2写法

vue.config.$store = store//全局,别的文件使用可以直接$store.commit('')在js里面使用this.$store.commit('')

window.vm = new Vue({ el: '#app', store, components: { App, }, template: '<App/>', });

//vue3写法我单独写一个笔记(因为vue3中的setup里面不能使用this)

app.use(store)//vue3写法,vue3中一般使用pinia也是一个仓管,比vuex少了一个mutations对象,具体区别还是可以看一下pinia官方文档

第三步 :就可以使用了,使用

    <h3>{{  $store.getters.showNum}}</h3>

    <button @click="$store.commit('increment')">+1</button>

    <button @click="$store.commit('incrementN',3)">+N</button> 

看完之后再看这个应该彻底明白了

扩展还有一种使用方法  就是这样,在使用文件里面写

import { mapState,mapMutations,mapActions,mapGetters } from 'vuex';

 computed:{

        ...mapState(['count']),

        ...mapGetters(['showNum'])

    },

    methods:{

        ...mapMutations(['increment']),

        ...mapActions(['addAsync',]),

}

个人理解笔记,如果有理解错误的,可以给我说

  • 59
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值