vue.resource 、axios、ajax

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')
          });

4、跨域,直接使用jsonp

this.$http.jsonp('../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);
             })
     })
}

注意

axios 不支持jsonp,所以必须另寻他路

常见的解决跨域的方法有几种:

  • jsonp
  • iframe
  • 代理
  • 反向代理

原文:https://segmentfault.com/a/1190000011275438

猜你喜欢

转载自blog.csdn.net/benben0729/article/details/87860110