vuex 使用方法

本文详细介绍了Vuex如何解决大型应用的数据存储和同步问题,重点讲解了Vuex的store、mutations、actions以及它们在异步操作中的应用。通过实例展示了如何使用Vuex进行状态管理和组件间的通信,包括在组件中如何调用mutations和actions,以及在computed属性中获取和响应状态变化。
摘要由CSDN通过智能技术生成

vuex 主要是用来解决大型系统的数据存储和同步问题。vuex的核心是store, store中的状态是响应式的,当state发生改变,页面使用的值会发生改变,页面会重新渲染。举个例子:

import { createApp } from 'vue'
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment(state, payload) {
      state.count = payload.amount;
    }
  },
  // action可以用来调用mutation方法
  actions: {
    increment(context) { // context可以解构为{dispatch, commit, state}
       context.commit('increment', {amount: 1});
       // 调用incre
       dispatch('incre');
    },
    incre() {
      ...
    } 
  }
})

const app = createApp({ /* 根组件 */ })

// 将 store 实例作为插件安装
app.use(store)

在程序中可以通过this.$store获取store实例并修改状态值:

import { mapMutations } from 'vuex'
methods: {
  increment() {
    this.$store.commit('increment', {amount: 1});
    console.log(this.$store.state.count);
  }
//  or 
  ...mapMutations[
    'increment', // 程序中使用this.increment({amount:1})
  ]
// or
  ...mapActions[
    add: 'increment', // 映射actions increment方法,程序中使用this.add({amount:1})
  ]

   dispatchFun() {
      this.$store.dispatch('increment', {amount: 1})
   }
}

 当状态发生改变的使用,在computed方法中获取最新状态:

import { mapState } from 'vuex'
// vuex将$store注入到根组件中,子组件均可使用
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed:{
   ...mapstate({
    count: state => state.count,
    // 名称相同时
    'count',
  })
  }
}

actions方法可以时异步方法,当为异步方法时举例:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

// 在程序中使用.then
this.$store.commit('actionA').then(res=>{})

// 使用 async await
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

this.$store.commit('actionA')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值