javascript - 如何在 vuex 中正确设置多个 api 调用?
问题描述
我正在使用 Laravel 开发一个大型 Web 应用程序。我为从 API 控制器接收数据的用户、供应商、项目、估计和服务创建了页面/组件。如果我需要在不使用道具的情况下重用其他组件中的数据,我想使用 Vuex。因此,我在 Vuex 中为供应商和用户设置了模块。
供应商模块:
import axios from "axios"
// state having some demo data
const state = {
erors: [],
success: [],
alert_created: '',
alert_success: '',
alert_error: '',
vendors: [],
};
const getters = {
};
const actions = {
async getVendors({ commit }, id) {
console.log(id)
await axios.get('/api/getvendordata')
.then(response => {
console.log(response.data.vendors)
commit('SET_VENDORS', response.data.vendors)
})
},
async editVendor( {commit, dispatch }, data, alert){
if(confirm('Are you sure?'))
{
await axios.post(`/api/vendors/${data.vendor.id}`, {
_method: 'patch',
name: data.form.name,
})
.then(response => {
commit('ALERT_SUCCESS', `Successfully edited!`)
dispatch('displaySuccess', alert)
dispatch("getVendors")
})
.catch(response => {
commit('ALERT_ERROR', `Could not edit!`)
dispatch('displayErrors', alert)
dispatch("getVendors")
})
}
},
async deleteVendor( {commit, dispatch}, data, alert) {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.delete(`/api/vendors/${data.id}`, {
__method: 'DELETE'
})
.then(response => {
// Show status message
commit('ALERT_SUCCESS', `Successfully deleted ${data.name}!`)
dispatch('displaySuccess', Alert)
dispatch("getVendors")
})
.catch(response => {
commit('ALERT_ERROR', `Could not delete!`)
dispatch('displayErrors', alert)
dispatch("getVendors")
})
});
},
async addVendor( {commit, dispatch}, form, alert) {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/api/vendors', {
name: form.name,
})
.then(response => {
// Show status message
commit('ALERT_SUCCESS', 'Successfully created new vendor!')
dispatch('displaySuccess', alert)
dispatch("getVendors")
})
.catch(response => {
commit('ALERT_ERROR', `Could not create!`)
dispatch('displayErrors', alert)
dispatch("getVendors")
})
});
},
displaySuccess({ commit }, alert) {
commit('SET_SUCCESS', alert)
},
displayErrors({commit}, alert){
commit('SET_ERROR', alert)
}
};
const mutations = {
ALERT_SUCCESS(state, msg) {
state.alert_success = msg
},
ALERT_ERROR(state, msg) {
state.alert_error = msg
},
SET_SUCCESS (state, alert) {
state.success.push(alert)
},
SET_ERRORS (state, msg){
state.errors.push(msg)
},
SET_VENDORS(state, vendors) {
state.vendors = vendors
},
};
export default{
state,
getters,
actions,
mutations
}
每个其他模块都有或多或少相同的代码。
解决方案
推荐阅读
- javascript - jQuery . 加载屏幕在 1 秒后没有消失
- c# - System.Serializable 将变量设置为零
- django - 有没有办法阻止 Django 自动将“_id”添加到外键
- javascript - 用于检查图像是否具有白色背景的 Javascript 画布循环
- python - 如何查找二叉树中是否存在值:对或错(Python3)
- node.js - npm ci 在 docker 中因 ProcessTerminatedError 而失败
- excel - 如何提取特定的id
- html - 我正在尝试将 HTML 音频添加到我的烧瓶网站,但音频栏显示为灰色
- unit-testing - 使用 bootstrap vue 失败的单元/Jest 测试
- javascript - 玩笑模拟不适用于 React 测试库