vue3中如何拆分axios函数和组件?
How to split axios functions and components in vue3?
我觉得把axios命令和vue组件分开比较好
这是我的目录结构:
src
api
- products.js
components
- Products.vue
products.js
import axios from 'axios';
const listProducts = () => {
const headers = { "Content-Type": "application/json" };
let url = "http://localhost:8001/api/v1/products";
const response = axios.get(url, headers);
return response.data
}
export default {
listProducts,
}
Products.vue
:
<template>
<div>{{ products }}</div>
</template>
<script>
import { listProducts } from "@/api/products.js"
export default {
data () {
return {
products: {},
}
},
created() {
this.getProducts();
},
methods: {
getProducts() {
this.products = listProducts();
}
}
}
</script>
但 this.products
未定义。我用异步和等待尝试了一些东西,但没有任何效果。
vue3 中的最佳实践是什么?
axios.get()
returns一个Promise
,所以下一行的response
实际上是一个Promise
(不是Axios响应本身):
const listProducts = () => {
⋮
const response = axios.get(url, headers);
return response.data // ❌ `response` is a `Promise`
}
要获得响应,您可以等待 axios.get()
调用的结果:
const listProducts = async () => {
⋮
const response = await axios.get(url, headers);
return response.data
}
同样,这个更新的 listProducts()
函数现在 returns 变成了 Promise
,因为它是 async
。您的组件现在必须等待 listProducts()
:
的结果
// Products.vue
export default {
⋮
methods: {
async getProducts() {
this.products = await listProducts();
}
}
}
我觉得把axios命令和vue组件分开比较好
这是我的目录结构:
src
api
- products.js
components
- Products.vue
products.js
import axios from 'axios';
const listProducts = () => {
const headers = { "Content-Type": "application/json" };
let url = "http://localhost:8001/api/v1/products";
const response = axios.get(url, headers);
return response.data
}
export default {
listProducts,
}
Products.vue
:
<template>
<div>{{ products }}</div>
</template>
<script>
import { listProducts } from "@/api/products.js"
export default {
data () {
return {
products: {},
}
},
created() {
this.getProducts();
},
methods: {
getProducts() {
this.products = listProducts();
}
}
}
</script>
但 this.products
未定义。我用异步和等待尝试了一些东西,但没有任何效果。
vue3 中的最佳实践是什么?
axios.get()
returns一个Promise
,所以下一行的response
实际上是一个Promise
(不是Axios响应本身):
const listProducts = () => {
⋮
const response = axios.get(url, headers);
return response.data // ❌ `response` is a `Promise`
}
要获得响应,您可以等待 axios.get()
调用的结果:
const listProducts = async () => {
⋮
const response = await axios.get(url, headers);
return response.data
}
同样,这个更新的 listProducts()
函数现在 returns 变成了 Promise
,因为它是 async
。您的组件现在必须等待 listProducts()
:
// Products.vue
export default {
⋮
methods: {
async getProducts() {
this.products = await listProducts();
}
}
}