vue.js - 在 vuex 中使用提交的最佳方式是什么?
问题描述
我每天都使用 vue 和 vuex 来创建我的项目,有时在发出 http 请求时,不需要创建状态突变。我用这种方式:
actions:{
theAction({},payload){
// bla bla
}
}
这样我会收到警告,但是我可以执行该操作。我已经能够观察到避免这个警告,有些人建议在组件内创建这个动作,因为我觉得这很乏味,因为理想的事情是处理来自状态的逻辑
我的问题是,创建这种操作的最佳实践是什么?
解决方案
如果您在许多组件中使用此接收到的数据,则应使用突变将其存储在状态中。如果您在某个组件中使用数据,但不想直接从该组件接收数据,可以将此调用放在放置所有此类请求的 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
}
}
推荐阅读
- java - 如何将数据从活动传递到android中的回收器视图适配器
- python - Python Flask avro 请求问题
- php - Laravel 在 null 上调用成员函数 first()
- javascript - classList 的 JavaScript 问题
- python - 有谁知道如何更改函数,以便仅将生成的列表输出到 csv,而 df 中的每一行都不会被范围内的数字分割?
- jboss - 当我有 1000 多个规则时,如何优化我的 Kiebase 构建时间?
- python - 尝试使用 Scrapy 抓取时出现 555 HTTP 协议
- azure-devops - Task.json azure devops 扩展隐藏输入
- python - python中的异步错误
- hugo - 在 hugo 中替换 .Page.UniqueID 以解决弃用警告