• axios调用接口


    axios调用接口

    1. 按照axios
    npm install --save-dev axios
    2.在main.js 引入axios,
    设置全局属性$http 指向axios

    main.js
    import axios from 'axios'
    Vue.prototype.$http = axios


    3.data中定义一个变量
    return {
    testData: []
    }
    }
    methods中定义调用API数据的方法
    methods: {
    getData () {
    // this是指向当前vue实例,千万不能丢掉,不然会报方法或对象undefined
    // 调用的接口是豆瓣公开的,可以直接测试调用
    this.$http.get('https://api.douban.com/v2/book/1220562').then(response => {
    this.testData = response.data
    }).catch(error => {
    console.log(error)
    })
    }
    }
    created 钩子用来在一个实例被创建之后执行该方法
    created () {
    this.getData()
    }

    4.webpack配置代理跨域
    config文件夹下的index.js中的proxyTable属性就是提供本地代理配置项,可根据Vue-cli使用插件介绍配置如下即可
    代码:
    proxyTable: {
    '/v2': {
    target: 'https://api.douban.com',
    changeOrigin: true,
    pathRewrite: {
    // /v2将代表target/v2
    '^/v2': '/v2'
    }
    }
    }
    5. 将url:'https://api.douban.com/v2/book/1220562'修改为:'/v2/book/1220562',修改完成

    6.

    组件数据展示

    将testData绑到template里,发现组件已经调用数据成功了

    完整代码:

    <template>
        <span>{{ testData }}</span>
    </template>
     
    <script>
    export default{
      data () {
        return {
          testData: []
        }
      },
      created () {
        this.getData()
      },
      methods: {
        getData () {
          // this是指向当前vue实例,千万不能丢掉,不然会报方法或对象undefined
          // 调用的接口是豆瓣公开的,可以直接测试调用
          this.$http.get('/v2/book/1220562').then(response => {
            this.testData = response.data
          }).catch(error => {
            console.log(error)
          })
        }
      }
    }
    </script><style type="text/css"></style>

    转载:

    https://www.2cto.com/kf/201801/714145.html

  • 相关阅读:
    接口测试之Postman简介
    postman发送get请求
    postman添加权限验证
    接口测试基础
    postman发送post请求
    postman测试上传文件
    1 R语言介绍
    《荣枯鉴》明鉴卷六
    《荣枯鉴》节仪卷五
    《荣枯鉴》交结卷四
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/9318657.html
Copyright © 2020-2023  润新知