【Vue】使用 axios 发送ajax 请求
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                在 Vue 中,您可以使用 axios 库来发送 AJAX 请求。以下是如何安装 axios 并在 Vue 组件中使用它的示例:
- 安装 axios:
 
npm install axios- 在 Vue 组件中引入 axios 并使用:
 
<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <div v-if="data">Fetched Data: {{ data }}</div>
  </div>
</template>
 
<script>
import axios from 'axios';
 
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    fetchData() {
      axios.get('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => {
          this.data = response.data;
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    },
  },
};
</script>在这个例子中,我们创建了一个按钮,当点击时,会触发 fetchData 方法。fetchData 方法使用 axios 发送 GET 请求到模拟的 JSON 服务器,并在成功获取数据时,将数据保存到组件的 data 属性中。如果请求失败,它会在控制台记录错误。
评论已关闭