gpt4 book ai didi

javascript - 调用后的Vuejs axios变量分配

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

我想从混合中使用 this.request(url) 调用 axios(以简化和集中有关 axios 的所有内容在同一个文件中),但它不起作用。

Vue文件:

export default {
name: "employees-list",
data() {
return {
employees: []
}
},
mounted() {
this.employees = this.request('https://jsonplaceholder.typicode.com/posts');
}
}

Request.js

Vue.mixin({
methods: {
request: function (url) {
axios.get(url)
.then(response => {
return response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
});

员工是“未定义的”。

我认为问题出在 async 或 await 上,但我不明白。

最佳答案

看起来您希望 mixin 创建一个通用方法来检索数据。在这种情况下,您需要从 request 方法返回 promise 并在成功回调中处理结果数据。

这是一个工作示例。

console.clear()

const EmployeesList = {
name: "employees-list",
template: `
<ul>
<li v-for="employee in employees">{{employee.title}}</li>
</ul>
`,
data() {
return {
employees: []
}
},
mounted() {
// obviously using posts here as an example instead of
// employees.
this.request('https://jsonplaceholder.typicode.com/posts')
// handle the promise success
.then(e => this.employees = e);
}
}

Vue.mixin({
methods: {
request: function(url) {
// return the promise
return axios.get(url)
.then(response => {
return response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
});

new Vue({
el: "#app",
components: {
EmployeesList
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
<employees-list></employees-list>
</div>

关于javascript - 调用后的Vuejs axios变量分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346619/

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