Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

ajax和vue

作者:视同仁寤戬   发布日期:2025-03-25   浏览:134

// 使用 Vue 和 Ajax 进行数据请求的示例

// 引入 Vue
import Vue from 'vue';

// 创建一个 Vue 实例
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    items: [] // 存储从服务器获取的数据
  },
  methods: {
    // 使用原生 XMLHttpRequest 发起 AJAX 请求
    fetchItems() {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
      xhr.onload = () => {
        if (xhr.status === 200) {
          this.items = JSON.parse(xhr.responseText);
        } else {
          console.error('Error fetching data');
        }
      };
      xhr.send();
    },

    // 使用 Axios 发起 AJAX 请求(推荐方式)
    fetchItemsWithAxios() {
      axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
          this.items = response.data;
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    }
  },
  mounted() {
    // 组件挂载完成后调用方法获取数据
    this.fetchItems(); // 或者 this.fetchItemsWithAxios();
  }
});

解释说明:

  1. Vue 实例:我们创建了一个 Vue 实例,并绑定了一个 DOM 元素 #app。在 data 中定义了两个属性:messageitems,其中 items 用于存储从服务器获取的数据。

  2. fetchItems 方法:使用原生的 XMLHttpRequest 发起 GET 请求,获取数据后将其解析为 JSON 并赋值给 items

  3. fetchItemsWithAxios 方法:推荐使用 Axios 库来发起 AJAX 请求,它提供了更简洁的 API 和更好的错误处理机制。通过 axios.get() 发起请求,并在成功时将响应数据赋值给 items

  4. mounted 钩子:当组件挂载完成后,自动调用 fetchItemsfetchItemsWithAxios 方法来获取数据。

  5. Axios:如果你选择使用 Axios,请确保先安装它 (npm install axios) 并引入到项目中。

注意:

  • 如果你不想使用 Axios,可以选择使用原生的 XMLHttpRequest,但 Axios 更加方便和易用。

上一篇:vue computed

下一篇:antdesignvue

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站