得到以下错误
state.products.push不是函数
import Vue from 'vue'
import Vuex from 'vuex'
const URL = "http://localhost:3000/products"
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
products: [],
success: null,
error: null
},
mutations: {
setAllProducts(state,payload){
state.products = payload
},
createAProduct(state, payload) {
const newProduct = payload
console.log(typeof state.products)
console.log(state)
state.products.push(newProduct)
},
setSuccess (state , payload) {
state.success = payload
},
setError (state, payload) {
state.error = payload
},
updateAProduct(state,payload) {
for( let product in state.products)
{
if(product.id == payload[1])
{
product.productName= payload[0].productName,
product.productDescription = payload[0].productDescription,
product.manufacturer = payload[0].manufacturer,
product.price = payload[0].price,
product.quantity = payload[0].quantity
}
}
}
},
actions: {
addNewProduct({ commit }, payload) {
const product = {
productName: payload.productName,
productDescription: payload.productDescription,
manufacturer: payload.manufacturer,
price: payload.price,
quantity: payload.quantity,
}
axios.post(`${URL}`, product)
.then((data) =>{
let key = data.id
commit('createAProduct',{...product,key})
commit('setSuccess', `${data.data.productName} is added to Products` )
})
.catch((error) =>{
console.log(error)
commit('setError', error )
}
)
},
updateProduct({commit}, payload)
{
const product = {
productName: payload[0].productName,
productDescription: payload[0].productDescription,
manufacturer: payload[0].manufacturer,
price: payload[0].price,
quantity: payload[0].quantity,
}
axios.put(`${URL}/${payload[1]}`,product)
.then((data)=>{
commit('updateAProduct', payload)
commit('setSuccess', `${data.data.productName} is updated successfully` )
})
},
addAllProducts( {commit }, payload)
{
commit('setAllProducts',payload)
}
},
getters:{
success (state) {
return state.success
},
error (state) {
return state.error
}
}
})
有效负载具有以下属性
键:12 制造商:“ H&M” 价格:“ 12” 产品描述:“ H&M的JAVAScript T恤” productName:“ Deepraj毛里雅” 数量:“ 12”
添加了整个index.js文件,请看一看。我只是在创建和更新产品
addAllProducts通过以下方法调用:
getAllProducts() {
axios
.get(`http://localhost:3000/products`)
.then((data) => {
console.log(typeof data)
console.log(data)
this.$store.dispatch("addAllProducts", data);
});
答案 0 :(得分:0)
发送data.products
getAllProducts(){ axios .get(http:// localhost:3000 / products) .then((数据)=> { console.log(数据类型) console.log(数据) this。$ store.dispatch(“ addAllProducts”,data.products); });。