zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Leetcode665.Non-decreasing Array非递减数组
    在MyEclipse中把多行代码用一快捷键注释掉
    struts2中addFieldError()方法
    [bzoj2588][Spoj10628]Count on a tree_主席树
    [bzoj3123][Sdoi2013]森林_主席树_启发式合并
    [bzoj1500][NOI2005]维修数列_非旋转Treap
    [bzoj1452][JSOI2009]Count_树状数组
    [bzoj1369][Baltic2003]Gem_树形dp_结论题
    [bzoj1195][HNOI2006]最短母串_动态规划_状压dp
    [bzoj2242][Sdoi2011]计算器_exgcd_BSGS
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/9318657.html
Copyright © 2011-2022 走看看