我正在将laravel 5.8与vue js一起使用。我为发布/获取请求创建了一个通用函数。问题是,我没有得到mixins函数响应。这是我的代码:
TestComponent.vue
import GeneralMixin from '../mixins.js';
export default {
mixins: [ GeneralMixin ],
methods:{
login: function (e) {
let response;
response = this.testMixin();
console.log(response);
}
}
}
mixin.js
export default {
methods: {
testMixin: function () {
url = '/test';
axios.post(url).then(function(response, status, request) {
return response;
});
}
}
}
控制台结果为undefined
我没有收到功能testMixin()
的响应。有人可以帮忙吗
答案 0 :(得分:1)
如果您想从mixin返回响应,则需要将该axios请求包装在promise中:
return new Promise((resolve, reject) => {
axios.post(url).then(function(response, status, request) {
return resolve(response)
})
})
如果您希望从另一个函数获得该结果:
login: function (e) {
this.textMixin().then((response) => {
console.log(response)
})
}
但是,实际上只返回诺言的响应是一种反模式。创建此混合的方式可作为psuedo-API供您内部使用,因此只需返回axios请求即可:
return axios.post(url)
现在您可以自己处理:
login: function(e) {
this.testMixin().then((response) => {
console.log(response)
}).catch((error) => {
console.log(error.response.data)
})
}
答案 1 :(得分:0)
您需要返回承诺,如下所示
在你混入
return axios.post(url);
现在在组件中按如下所示使用它。
this.testMixin().then((response) => {
console.log(response)
}).catch((error) => {
console.log(error.response.data)
})