天天看点

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

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

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

})

})

}