前端框架Vue(3)—— vue.resource 、axios、ajax 异步通信

本文探讨了在Vue中进行异步通信的方法,包括使用$.ajax()(依赖jQuery)、vue-resource(已停止更新)和推荐的axios。介绍了在Vue项目中引入和使用这些库的步骤,重点推荐了axios,并提供了axios的GitHub地址。
摘要由CSDN通过智能技术生成

vue 中如何支持异步请求

1、vue 支持开发者引入 jquery 使用 $.ajax()

1、首先,在 package.json 中添加 jQuery,然后 npm install

"dependencies": {
    "jquery": "^3.2.1",
  },

2、在 webpack.config.js ( 这边用的 vue-cli-simple 脚手架 )

 // 增加一个plugins
  plugins: [
      new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery"
      })
   ],

3、最后,在全局(main.js)中去引用

import $ from 'jquery'   

2、vue.resource( 2.0后不再更新)

1、 npm 安装 vue-resource

 npm install vue-resource

2、 main.js 中引入

 import VueResource from 'vue-resource'
  Vue.use(VueResource)

3、使用

this.$http.get('../src/data/a.txt')
    .then(function(res){
              alert(res.data);
          },function(){
              alert('false')
          });



3、推荐使用 axios

github 地址:https://github.com/mzabriskie/axios

url :绝对路径

1、npm 安装

npm install axios

2、组件 中引入

import Vue from 'vue'
import Axios from 'axios'

3、使用

axios.get('url')
     .then(function(res){
    alert(res);
     })
     .catch(function(err){
    alert(err);
     })
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
 mounted: function() {
     this.$nextTick(function () {
    //先定义一个全局_this
        var _this=this;
        axios.get('../../src/data/a.txt')
             .then(function(res){
                  _this.msg=res.data;
                  console.log(_this.msg)
             })
             .catch(function(err){
                  alert(err);
             })
     })
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值