首页 > 解决方案 > 在 vuex 中使用提交的最佳方式是什么?

问题描述

我每天都使用 vue 和 vuex 来创建我的项目,有时在发出 http 请求时,不需要创建状态突变。我用这种方式:

actions:{
   theAction({},payload){
      // bla bla
   }
}

这样我会收到警告,但是我可以执行该操作。我已经能够观察到避免这个警告,有些人建议在组件内创建这个动作,因为我觉得这很乏味,因为理想的事情是处理来自状态的逻辑

我的问题是,创建这种操作的最佳实践是什么?

标签: vue.jsvuex

解决方案


如果您在许多组件中使用此接收到的数据,则应使用突变将其存储在状态中。如果您在某个组件中使用数据,但不想直接从该组件接收数据,可以将此调用放在放置所有此类请求的 api 文件夹中某个单独的 js-module 中。

更新:

这是来自 api 文件夹的 js-module 示例:items.js

import axios from 'axios'

export default {
  async getItems (options) {
    const { data: result } = await axios.post('/api/items', options)
    return result
  }
}

用法:MyComponent.vue

import itemsApi from '@/api/items'
...
export default {
...
data () {
  return {
    items: []
  }
},
methods: {
   async loadItems() {
      this.items = await itemsApi.getItems({})
  }
}

如果您希望在多个组件中使用此 API,您可以使用此 loadItems 函数创建 mixin。

这是状态模块 items.js 的动作和突变的示例:

import itemsApi from '@/api/items'

const GET_ITEMS = 'GET_ITEMS'

const state = {
  items: []
}

const actions = {
  async getItems ({ commit }, params) {
    const items = await itemsApi.getItems(params)
    commit(GET_ITEMS, items)
  },
}
const mutations = {
  [GET_ITEMS] (state, items) {
    state.items = items
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}

用法:

我的组件.vue

<script>
import { mapActions, mapState } from 'vuex'
...
export default {
...
computed: {
  ...mapState({
    items: state => state.items.items
  }),
},
methods: {
   ...mapActions({
     getItems: 'items/getItems',
    }),
   async loadItems() {
      await this.getItems({})
      // now you have the loaded items in this.items
  }
}

推荐阅读