My component is like this :
<script>
export default{
props:['search','category','shop'],
...
methods: {
getVueItems: function(page) {
this.$store.dispatch('getProducts', {q:this.search, cat:this.category, shop: this.shop, page:page}).then(response => {
console.log(response)
this.$set(this, 'items', response.body.data)
this.$set(this, 'pagination', response.body)
}, error => {
console.error("this is error")
})
},
...
}
}
</script>
The ajax call getProducts method on the product.js module
The product.js module is like this :
import { set } from 'vue'
import product from '../../api/product'
import * as types from '../mutation-types'
// initial state
const state = {
list: {}
}
// actions
const actions = {
getProducts ({ commit,state }, payload)
{
product.getProducts( payload,
data => {
let products = data
commit(types.GET_PRODUCTS,{ products });
},
errors => {
console.log('error load products ')
}
)
}
}
// mutations
const mutations = {
[types.GET_PRODUCTS] (state, { products }) {
state.list = {}
products.data.forEach(message => {
set(state.list, message.id, message)
})
}
}
export default {
state,
actions,
mutations
}
Then, the module call getProducts method again on the product.js api
The product.js api is like this :
import Vue from 'vue'
import Resource from 'vue-resource'
Vue.use(Resource)
export default {
// api to get filtered products
getProducts (filter, cb, ecb = null ) {
Vue.http.post(window.Laravel.baseUrl+'/search-result',filter)
.then(
(resp) => cb(resp.data),
(resp) => ecb(resp.data)
);
}
}
When executed, I check on the console, the response not show. The response undefined
How can I solve the error?
UPDATE
If I use normal ajax like this :
<script>
export default{
props:['search','category','shop'],
...
methods: {
getVueItems: function(page) {
const q = this.search
const cat = this.category
const shop = this.shop
this.$http.get('search-result?page='+page+'&q='+q+'&cat='+cat+'&shop'+shop).then((response) => {
console.log(JSON.stringify(response))
this.$set(this, 'items', response.body.data)
this.$set(this, 'pagination', response.body)
});
},
...
}
}
</script>
It works. It get the response
But, Why when I use vuex store, it does not work?
You should return an Promised
in your actions
.
Try:
// actions
const actions = {
getProducts ({ commit,state }, payload)
{
return new Promise((resolve, reject) => {
product.getProducts( payload,
data => {
let products = data
commit(types.GET_PRODUCTS,{ products });
resolve(data)
},
errors => {
console.log('error load products ')
reject(errors)
}
)
})
}
}
or simply, you could just pass return Vue.http.post()
up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With