gpt4 book ai didi

javascript - 如何在 vue.js 2 上获得 this.$store.dispatch 的响应?

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:11 26 4
gpt4 key购买 nike

我的组件是这样的:

<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>

ajax调用product.js模块的getProducts方法

product.js 模块是这样的:

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
}

然后,模块再次调用 product.js api 上的 getProducts 方法

product.js api 是这样的:

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)
);
}
}

执行时,我在控制台上查看,没有显示响应。未定义的响应

如何解决错误?

更新

如果我像这样使用普通的 ajax :

<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>

它有效。它得到响应

但是,为什么当我使用 vuex store 时,它​​不起作用?

最佳答案

您应该在您的操作中返回一个Promised

尝试:

// 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)
}
)
})
}
}

或者简单地说,您可以将 return Vue.http.post() 向上传递。

关于javascript - 如何在 vue.js 2 上获得 this.$store.dispatch 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com