vue中封装async公用函数
时间: 2024-01-26 16:05:06 浏览: 35
在Vue中,我们可以将异步操作封装在一个公用的函数中,然后在需要的地方进行调用。以下是一个简单的示例:
```js
// api.js
export async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
return data.title;
}
```
```vue
<template>
<div>
<p>{{ message }}</p>
<button @click="getData">获取数据</button>
</div>
</template>
<script>
import { fetchData } from '@/api.js';
export default {
data() {
return {
message: ''
}
},
methods: {
async getData() {
try {
this.message = await fetchData();
} catch (error) {
console.error(error);
}
}
}
}
</script>
```
在上述示例中,我们将异步获取数据的操作封装在了api.js文件中的fetchData函数中,并导出该函数。然后,在Vue组件中引入该函数,并在需要的地方进行调用。
这种方式将异步操作封装在一个公用的函数中,既避免了代码冗余,又增加了代码的可复用性。同时,由于异步操作在公用函数中进行,也更易于进行错误处理和调试。