vuex的用法

本文详细介绍了Vue.js中状态管理库Vuex的安装、配置和使用方法,包括state、mutations、getters、actions及modules的实战应用,强调了它们在组件间共享数据和管理状态的角色,并提供了具体的代码示例。通过Vuex,可以更好地组织和管理大型Vue项目的复杂状态。

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

为什么要使用vuex

当我们使用vue的时候,各个组件可能要共享一份信息,例如用户信息等,所以就需要使用vuex,vuex就是来共享信息的。

安装vuex

npm install vuex --save

配置vuex

1.在src目录下创建一个文件夹store
2.src/store下创建index.js

index.js

import Vue from 'vue'//引用vue
import Vuex from 'vuex'//引用vuex
//安装插件
Vue.use(Vuex)
//创建对象
const store = new Vuex.Store({
    state:{
        //state是存数据的
        counter:100
    },
    mutations:{
        //mutations是用来改变state里面的数据的
    },
    getters:{
        //getters类似于computed
    },
    actions:{
        //用来进行异步操作的
    },
    modules:{
        //注册小组件的
    }
})
//导出
export default store

使用

src/main.js

//导入
import store from './Store'
注册
new Vue({
  el: '#app',
  router,
  //使用
  store,
  render: h => h(App)
})

state的使用

state:{
        //state是存数据的
        counter:100
}

App.vue使用

<h2>{{$store.state.counter}}</h2>

mutations的使用

mutations:{
        //mutations是用来改变state里面的数据的
        increment(state){
            state.counter++
        },
        //传参
        //payload是一个对象,将参数存在这个对象里面
        incrementCount(state,payload){
            state.counter+=payload.count
        }
    }

App.vue

<button @click="add">+</button>
<button @click="addCount(5)">+5</button>
add(){
      //通过使用this.$store.commit(),传入的是待使用的mutations
      this.$store.commit('increment')
},
addCount(count){
      //1.普通的提交风格
      //传入第二个数为参数
      this.$store.commit('incrementCount',count)

      //2.特俗的提交风格
      this.$store.commit({
        type: 'incrementCount',
        count: count
      })
    }

getters的使用

getters:{
        //getters类似于computed
        powercounter(state){
            return state.counter*state.counter
        }
},

App.vue

<h2>{{$store.getters.powercounter}}</h2>

actions的使用

actions:{
        //用来进行异步操作的
        //context就是store,context打印里面有很多属性
        //context:{f:commit(),f:dispatch(),getters,rootGetters(父组件的getters),rootState(父组件的State),state}
        aUpdateInfo(context,payload){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    //因为context就是store,所以可以使用commit,类似于上面使用mutations中的this.$store.commit
                    context.commit('updateInfo')
                    console.log(payload)
                    resolve('我已经完成了任务')
                },1000)
            })
        }

    },

App.vue

<button @click="updateInfo">改变名字</button>
updateInfo(){
      // this.$store.dispatch('aUpdateInfo')
      
      //携带参数
      // this.$store.dispatch('aUpdateInfo',{
      //   message: 'Nihao',
      //   success: ()=>{
      //     console.log('你好呀')
      //   }
      // })

      this.$store.dispatch('aUpdateInfo','我是携带的信息').then(res=>{
        console.log(res)
      })
    },

modules的使用

modules:{
        //注册小组件的
        a: moduleA
    }
const moduleA={
    state:{
        name: '张山'
    },
    mutations:{
        updateName(state,payload){
            state.name = payload
        }
    },
    actions:{
        aUpdateName(context){
            console.log(context)
            setTimeout(()=>{
                context.commit('updateName','wangwu')
            },1000)
        }

    },
    getters:{
        fullname(state){
            return state.name+'111'
        },
        //getters就是这个组件的getters
        fullname2(state,getters){
            return getters.fullname+'222'
        },
        //module里面的getters的使用/使用rootState获得父组件的
        fullname3(state,getters,rootState){
            return getters.fullname2+rootState.counter
        }
    }
}

使用
App.vue

//module里面的name的使用
<h2>{{$store.state.a.name}}</h2>

//module里面的mutations的使用,和父组件的使用方法一样,所以注册的时候不要重名
<button @click="updatename">module/mutations</button>

//module里面的getters的使用,也不要重名
<h2>{{$store.getters.fullname}}</h2>
<h2>{{$store.getters.fullname2}}</h2>
<h2>{{$store.getters.fullname3}}</h2>

<button @click="asyncUpdateName">Module里面的异步操作</button>
updatename(){
      this.$store.commit('updateName','niniini')
},
asyncUpdateName(){
      this.$store.dispatch('aUpdateName')
}

总结:
1. 可以看出父组件和子组件是共用mutations和dispatch的,所以命名的时候不要重名。
2. mutations使用是用store的commit函数
3. actions使用的是store的dispatch函数
4. context其实就是store,不懂用context就打印看一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值