vue.js - 将 Axios 调用的结果添加到 State
问题描述
这是一个非常基本的问题,但我没有得到任何地方......
用 Vue 和 Vuex 做一个简单的购物车。我在状态中对产品进行了硬编码,但现在我正在尝试进行 axios 调用并将该结果添加到状态中。我有 axios 函数,我正在尝试加载该函数并将 JSON 结果附加到数组all
中。
如何将 loadItems() 的结果放入all
数组中?谢谢
编辑:我已经更新了我的整个 vuex 文件。
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import * as types from './mutation-types'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
// axios call
const api = {
loadItems() {
// Init variables
var self = this
var app_id = "asdfasf";
var app_key = "asdfasfaf";
this.items = []
axios.get(
"https://api.airtable.com/v0/"+app_id+"/Products",
{
headers: { Authorization: "Bearer "+app_key }
}
).then(function(response){
self.items = response.data.records.map((item)=>{
return {
id: item.id,
...item.fields
}
})
}).catch(function(error){
console.log(error)
})
}
}
// initial state
const state = {
added: [],
all: []
}
// getters
const getters = {
allProducts: state => state.all, // would need action/mutation if data fetched async
getNumberOfProducts: state => (state.all) ? state.all.length : 0,
cartProducts: state => {
return state.added.map(({ id, quantity }) => {
const product = state.all.find(p => p.id === id)
return {
name: product.name,
price: product.price,
quantity
}
})
}
}
// actions
const actions = {
addToCart({ commit }, product){
commit(types.ADD_TO_CART, {
id: product.id
})
},
removeFromCart({ commit }, product){
commit(types.REMOVE_FROM_CART, {
id: product.id
})
}
}
// mutations
const mutations = {
[types.ADD_TO_CART] (state, { id }) {
const record = state.added.find(p => p.id === id)
if (!record) {
state.added.push({
id,
quantity: 1
})
} else {
record.quantity++
}
},
[types.REMOVE_FROM_CART] (state, { id }) {
const record = state.added.find(p => p.id === id)
if (!record) {
state.added.pop({
id,
quantity: 1
})
} else {
record.quantity--
}
},
}
// one store for entire application
export default new Vuex.Store({
state,
strict: debug,
getters,
actions,
mutations
})
解决方案
这是实现目标的一个小方法:
您可以使用 state.yourStateNameVariable 访问,或者更好地创建一个 getter 并提交从该状态获取/设置值。
观察:[types.ADD_TO_CART] 不是提交的好名字,可能是 addToCart 和 removeFromCart?
您不需要保存来自 axios 的响应的项目,您可以在解析后直接使用 state.all = yourdata 或更好的方式发送到所有状态,添加突变
setAllData({ state }, data){
state.all = data
}
我没有修复你所有的代码,但这里有一个方法:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import * as types from './mutation-types'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
state:{
added: [],
all: [
{
id: 'cc919e21-ae5b-5e1f-d023-c40ee669520c',
name: 'COBOL 101 vintage',
description: 'Learn COBOL with this vintage programming book',
price: 399
},
{
id: 'bcd755a6-9a19-94e1-0a5d-426c0303454f',
name: 'Sharp C2719 curved TV',
description: 'Watch TV like never before with the brand new curved screen technology',
price: 1995
},
{
id: '727026b7-7f2f-c5a0-ace9-cc227e686b8e',
name: 'Remmington X mechanical keyboard',
description: 'Excellent for gaming and typing, this Remmington X keyboard ' +
'features tactile, clicky switches for speed and accuracy',
price: 595
}
]
},
getters: {
allProducts: state => state.all, // would need action/mutation if data fetched async
getNumberOfProducts: state => (state.all) ? state.all.length : 0,
cartProducts: state => {
return state.added.map(({ id, quantity }) => {
const product = state.all.find(p => p.id === id)
return {
name: product.name,
price: product.price,
quantity
}
})
}
},
mutations: {
setAllData({ state }, data){
state.all = data
},
[types.ADD_TO_CART] ({ state }, id) {
const record = state.added.find(p => p.id === id)
if (!record) {
state.added.push({
id,
quantity: 1
})
} else {
record.quantity++
}
},
[types.REMOVE_FROM_CART] ({ state }, id) {
const record = state.added.find(p => p.id === id)
if (!record) {
state.added.pop({
id,
quantity: 1
})
} else {
record.quantity--
}
}
},
actions:{
loadItems({getters, commit}, somethingYouReceive) {
// Init variables
var self = this
var app_id = "adsfasfasgag";
var app_key = "agasdgagasgasg";
this.items = []
axios.get(
"https://api.airtable.com/v0/"+app_id+"/Products",
{
headers: { Authorization: "Bearer "+app_key }
}
).then(function(response){
commit('setAllData',response.data.records.map((item)=>{
return {
id: item.id,
...item.fields
}
})
}).catch(function(error){
console.log(error)
})
},
addToCart({ commit }, product){
commit(types.ADD_TO_CART, {
id: product.id
})
},
removeFromCart({ commit }, product){
commit(types.REMOVE_FROM_CART, {
id: product.id
})
}
}
})
推荐阅读
- python - 在 IPython 中使用自定义样式在函数内部显示熊猫数据框
- c# - Entity Framework Core 试图将自定义类型转换为其他自定义类型 (InvalidCastException)
- python - 基于 DataFrame 中另一列的列的滚动总和
- android - Phonegap:如果第一次被拒绝,请再次请求许可
- google-cloud-platform - GCP - 无法打印身份令牌
- azure - Azure AD B2C 注销不会使令牌无效
- java - 如何修复应用程序构造函数中的异常
- minikube - 实现路由转发方法的问题
- pandas - 添加到数据框时电子邮件正文被切断
- jquery - 多用户同时提问的问答式聊天界面