Vuex使用

本文详细介绍了Vuex状态管理模式在Vue.js应用程序中的使用方法。包括state、getters、mutations及actions的基本概念和实现方式,同时提供了插件推荐,如状态持久化、同步标签页等,帮助开发者更好地管理和维护应用状态。

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

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

在这里插入图片描述
1.state
当需要拿state里数据的时候

import {mapState} from 'vuex'
// import vuex from 'vuex'
// const mapState = vuex.mapState

computed: {
  ...mapState({
    formValidate: state => state.booking.order,
    dispatchList: state => state.dispatch.dispatchList
  }),

2.Getters
Store里创建方法

getters: {
ordergetters: (state) => {
return ‘orderID为:’ + state.order.orderId + ’ getters被调用了’
}
},
Getters实际上就是state的computed
…mapGetters([
‘ordergetters’
]),

然后像computed一样使用。
好处就是当一个store的state数据要在多个组件当中使用,就最好定义在getters里面,然后想上面一样使用就好了。
Computed默认情况下只有一个getter,没有setter
3 Mutations

porChange (porOption) {
  if (porOption) {
    // this.formValidate.seaInfo.por = porOption.pointCode
    this.$store.commit('porChanged', porOption.pointCode)
  } else {
    // this.formValidate.seaInfo.por = ''
    this.$store.commit('porChanged', ‘’)
  }
},
Booking.js
porChanged (state, params) {
  state.order.seaInfo.por = params
},

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

...mapMutations([
  'porChanged'
]),
porChange (porOption) {
  if (porOption) {
    this.porChanged(porOption.pointCode)
  } else {
    this.porChanged()
  }
},

4 actions
如果是异步请求,就是需要从接口中获取值的话,然后去修改state的话,就需要使用actions。

askingSearch (pageNum) {
  this.$store.dispatch('rfqAsingGetList', {
    pageNum: pageNum || this.askingList.pageNum,
    param: this.param,
    success: (data) => {
      const ids = []
      for (let i in data.list) {
        ids.push(data.list[i].askingId)
      }
      if (ids.length > 0) {
        this.$store.dispatch('rfqQuotationGetList', {
          askingIds: ids
        })
      }
    }
  })
},

然后actions里写请求的信息,

actions: {
  rfqAsingGetList (context, arg) {
    http.post(`/ms/ask/list.gou?pageNum=${isNaN(arg.pageNum) ? 1 : arg.pageNum}&pageSize=10`, arg.param).then(function (res) {
      // console.log(res)
      context.commit('_rfqAsingSetList', res.data.content)
      arg.success && arg.success(res.data.content)
    })
  },

通过commit去提交一个Mutations去修改store的值。

mutations: {
  _rfqAsingSetList (state, list) {
    state.list = list
  },

5插件
https://segmentfault.com/a/1190000012184535?utm_source=tag-newest
状态持久化https://github.com/robinvdvleuten/vuex-persistedstate
同步标签页、窗口https://github.com/xanf/vuex-shared-mutations
语言本地化https://github.com/dkfbasel/vuex-i18n
管理多个加载状态https://github.com/f/vue-wait
缓存操作https://github.com/superwf/vuex-cache

当数据需要持久化存储的时候,也就是当刷新浏览器改变的数据不会被改变的时候,就使用插件。

import saveInlocal from './plugin/saveInLocal'
在我们的store注册的地方也就是index.js里面使用这个插件。
plugins: [saveInlocal],

export default store => {
  if (localStorage.state) store.replace(JSON.parse(localStorage.state))
  store.subscribe((mutations, state) => {
    localStorage.state = JSON.stringify(state)
  })
}

6.v-model
我们在组件里想v-model state里的值的时候,不能使用直接赋值的形式。
而要使用get和set方法,使用get来获取state的值,,当要修改的时候,就使用set方法提交一个Mutations来改变那个值。

<CtnSetting v-model="containerList" :node="CtnNode.CONTAINER_NODE_PRE_BOOKING" :editCtnNo="false"></CtnSetting>


computed: {
containerList: {
  get: function () {
    return this.$store.state.booking.preBookingCtnList
  },
  set: function (val) {
    this.$store.commit('initPreBookingCtn', val)
  }
},

mutations: {
initPreBookingCtn (state, list) {
  state.preBookingCtnList = list
},
### Vuex 使用指南及实现状态管理示例 Vuex 是一个专为 Vue.js 应用设计的状态管理库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化[^1]。以下是关于 Vuex 的核心概念和使用方法的详细说明。 #### 1. 核心概念 Vuex 的核心概念包括以下几个部分: - **State**:用于存储共享的状态数据。 - **Getter**:类似于 Vue 组件中的计算属性,用于从 state 中派生出一些状态。 - **Mutation**:用于同步地修改 state 的方法。 - **Action**:类似于 mutation,但可以包含异步操作,最终会提交 mutation 来改变 state。 - **Module**:将 store 分割成模块,使代码更易于维护。 #### 2. 创建 Vuex Store 在项目中创建一个 `store.js` 文件,定义 Vuex 的 store: ```javascript // store.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { count: 0 // 示例状态 }, getters: { doubleCount(state) { return state.count * 2; // 计算属性示例 } }, mutations: { increment(state) { state.count++; // 同步修改状态 } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); // 异步操作后提交 mutation }, 1000); } } }); ``` #### 3. 在 Vue 实例中引入 Store 在 `main.js` 文件中引入并挂载 store: ```javascript // main.js import Vue from 'vue'; import App from './App.vue'; import store from './store'; new Vue({ store, // 挂载 store render: h => h(App) }).$mount('#app'); ``` #### 4. 在组件中使用 Vuex 通过 `mapState`、`mapGetters`、`mapMutations` 和 `mapActions` 辅助函数简化对 Vuex 的访问: ```javascript <template> <div> <p>Count: {{ count }}</p> <p>Double Count: {{ doubleCount }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { computed: { ...mapState(['count']), // 映射 state 到本地计算属性 ...mapGetters(['doubleCount']) // 映射 getter 到本地计算属性 }, methods: { ...mapMutations(['increment']), // 映射 mutation 到本地方法 ...mapActions(['incrementAsync']) // 映射 action 到本地方法 } }; </script> ``` #### 5. 状态持久化 未进行持久化配置可能导致状态丢失、数据不一致或重复操作等问题[^3]。可以通过插件如 `vuex-persistedstate` 实现状态持久化: ```javascript // store.js import createPersistedState from 'vuex-persistedstate'; export default new Vuex.Store({ state: { count: 0 }, plugins: [createPersistedState()] // 添加持久化插件 }); ``` 这样,即使页面刷新,状态也会被保存到 localStorage 或 sessionStorage 中。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值