21.Vue Ajax框架vue-resource&axios

  vue的ajax框架有vue-resource和axios;

  vue-resource插件非官方库,目前vue1,2都支持;

  axios是ajax通用请求库,vue官方推荐;

vue-resource:

  主页:https://github.com/pagekit/vue-resource

  安装下vue-resource,命令:npm install vue-resource
在这里插入图片描述
  main.js里全局引入,使用该插件;

import VueResource from 'vue-resource'

  声明使用插件 底层会给vm和组件对象添加一个属性 $http

/*
入口js:创建Vue实例
 */
import Vue from 'vue'
import App from './App'
import VueResource from 'vue-resource'
Vue.use(VueResource)
new Vue({
  el:'#app',
  components:{
    App
  },
  template:'<App/>'
})

  App里我们测试一个接口;

let url = 'http://localhost:8080/queryAll';
this.$http.get(url).then(response =>{
  // 请求成功
  console.log('success')
  console.log(response)
},response =>{
  // 请求失败,比如404
  console.log('error')
  console.log(response)
});

  编写了一个请求接口用来测试调用:

package com.vue.demo.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class VueController {
    //前后的分离的情况下,需要处理跨域
    @CrossOrigin(origins = "*",maxAge = 3600)
    @RequestMapping(value = "/queryAll")
    public String create(){
        List<Map> maps = new ArrayList<>();
        Map map1 = new HashMap();
        map1.put("id",1);
        map1.put("name","张三");
        Map map2 = new HashMap();
        map2.put("id",2);
        map2.put("name","王五");
        Map map3 = new HashMap();
        map3.put("id",3);
        map3.put("name","李四");
        maps.add(map1);
        maps.add(map2);
        maps.add(map3);
        return "{\"data\":" + JSON.toJSONString(maps) + ",\"code\": 查询成功 }";
    }
}

  请求成功:
在这里插入图片描述
  请求失败:http://localhost:8080/queryAll2 ,把路径改下
在这里插入图片描述
  具体详细用法,请看文档:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

axios:

  主页:https://github.com/axios/axios

  安装下axios,命令:npm install axios
在这里插入图片描述
  axios是哪里用到哪里引入;

import axios from 'axios'

  axios调用接口:

let url = 'http://localhost:8080/queryAll';
axios.get(url).then(response => {
  //请求成功
    console.log('success')
    console.log(response)
}).catch(error => {
  //请求失败
    console.log('error')
    console.log(response)
});

  请求成功:
在这里插入图片描述
  请求失败:http://localhost:8080/queryAll2 ,把路径改下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值