I'm building shopping cart where some data between components needs to be shared - I build some kind of simple State management to keep from using Vuex which is pretty hard to understand, and It works.
The State management works in this way:
1.First of I create separated store/state file which is vanilla js (I'm using lodash)
import _ from 'lodash'
export default {
data: {
bag: []
},
add(item) {
let found = _.find(this.data.bag, ['artnr', item.ID])
if ( !found ) {
this.data.bag.push({
artnr: item.ID,
name: item.post_name,
qty: 1
})
} else {
found.qty++
}
}
}
2.In my view component I import the State/Store file
import Store from '../stores/BagStore'
So then I create new data object property, called shared and assign data to Store.data
data() {
return {
item: [],
shared: Store.data
}
}
3.And at the end I have basic method that use method from state
methods: {
addItem() {
Store.add(this.item)
}
}
And this thing work perfect, but I want to make a POST HTTP Request too, which would store data in database via API, and if user reload page the items he added should be here.
We built API in Laravel, that requure to pass 2 values (artnr and qty), I tried to make something like this
methods: {
addItem() {
Store.add(this.item)
BagService.create(this.shared)
.then(shared => {
this.$dispatch('itemWasAdded', shared.data)
})
}
}
But then I got error
422 (Unprocessable Entity) The fields artnr and qty are required
Any idea, or better approach are welcome.Thanks.
Just log the contents you are sending to the server. It looks like it's this.shared
. You'll see it's not the content you expect it to be. The server is likely expecting an item, and you're sending an array of items.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.