vue3中如何请求接口数据
时间: 2023-05-29 12:01:36 浏览: 928
Vue3中可以使用axios、fetch、XHR等方式请求接口数据,以下是一个使用axios请求接口数据的示例代码:
```
import axios from 'axios'
export default {
name: 'Example',
data() {
return {
loading: false,
data: null,
error: null
}
},
mounted() {
this.loadData()
},
methods: {
loadData() {
this.loading = true
axios.get('/api/data')
.then(res => {
this.data = res.data
this.loading = false
})
.catch(err => {
this.error = err.message
this.loading = false
})
}
}
}
```
在上述代码中,我们在mounted钩子函数中调用loadData方法来请求接口数据。loadData方法中使用axios进行数据请求,并将返回的数据保存在data中。如果请求出现错误,会将错误信息保存在error中。同时,我们将loading标志用于标记当前是否在加载数据。
相关问题
vue3组件请求接口数据
1. 安装axios和vue-property-decorator
```
npm i axios vue-property-decorator
```
2. 创建一个组件,比如MyComponent.vue
```vue
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import axios from "axios";
@Component({})
export default class MyComponent extends Vue {
items: any[] = [];
created() {
this.fetchData(); // 获取数据
}
async fetchData() {
const res = await axios.get("http://example.com/api/items"); // 发送请求
this.items = res.data; // 更新数据
}
}
</script>
```
3. 在需要使用MyComponent的页面中导入组件
```vue
<template>
<div>
<h1>My App</h1>
<my-component></my-component>
</div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import MyComponent from "@/components/MyComponent.vue"; // 导入组件
@Component({
components: {
MyComponent, // 注册组件
},
})
export default class App extends Vue {}
</script>
```
4. 执行npm run serve运行项目,即可看到数据渲染在页面上。
vue3中如何使用fetch请求接口数据
1. 在组件中引入fetch方法:import fetch from 'unfetch';
2. 在vue3中使用setup函数来定义组件,传入context对象中的attrs属性,获取属性中的接口地址:
setup(props, {attrs}) {
const apiUrl = attrs.apiUrl;
...
}
3. 使用async/await关键字,调用fetch方法进行接口请求,获取数据:
async function fetchData() {
const response = await fetch(apiUrl);
const data = await response.json();
return data;
}
4. 将数据绑定到组件上:
setup(props, {attrs}) {
const apiUrl = attrs.apiUrl;
const data = ref([]);
onMounted(async() => {
data.value = await fetchData();
});
return {data};
}
5. 在模板中使用v-for指令来遍历data数据:
<div v-for="(item, index) in data" :key="index">{{item}}</div>
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)