• vue中Axios请求豆瓣API数据并展示到Swipe中


    vue中Axios请求豆瓣API数据并展示到Swipe中

    • 1.首先是安装Axios;
      安装方法cnpm install axios --save 等待npm安装完毕;

    • 2.在main.js中引入axios引入方法;
      import Axios from 'axios'

      Vue.prototype.$axios = Axios 必须要这样引入才能使用

    全部的main.js方法如下
    ```javascript
    

    // The Vue build version to load with the import command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    import Axios from 'axios'
    import './lib/css/mui.min.css'
    import './lib/css/icons-extra.css'
    import 'mint-ui/lib/style.css'
    import { Header } from 'mint-ui'
    import { Swipe, SwipeItem } from 'mint-ui';
    Vue.component(Swipe.name, Swipe);
    Vue.component(SwipeItem.name, SwipeItem);
    import router from './router'
    import App from './App'
    Vue.prototype.$axios = Axios
    Vue.prototype.HOST = "/api"
    Vue.config.productionTip = false
    Vue.component(Header.name, Header)
    /* eslint-disable no-new */
    new Vue({
    render: h => h(App),
    router
    }).$mount('#app');

    
    - 3.引入以后要做post请求数据封装处理;
    
    - 4.封装处理post请求后,要做跨域问题处理;
    	找到config目录下的index.js文件,然后找到proxyTable,进行修改,修改内容如下:
    

    proxyTable: {
    '/api': {
    target: 'https://api.douban.com',//设置你调用的接口域名和端口号 别忘了加http
    changeOrigin: true,
    pathRewrite: {
    '^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替
    },
    changeOrigin:true
    }
    },

    - 5.做完第4步后需要修改main.js;在main.js中增加一行代码;
    

    Vue.prototype.HOST = "/api"

    - 6.然后在其他模块中就可以直接调用了
    如:获取电影Top250 第一页 2条数据:
    豆瓣API:https://api.douban.com/v2/movie/top250?start=0&count=2
    
    然后可以在HomeContainer.vue中做如下代码:
    
    
    ##注意如下几点:
    #####main.js中文件的Axios的配置信息
    
    import Axios from 'axios'
    
    Vue.prototype.$axios = Axios
    Vue.prototype.HOST = "/api"
    
    vue中使用跨域url请求则请求地址可以如下写法
    `var url = this.HOST + "/v2/movie/in_theaters?city=广州&start=0&count=3"`
    ####注意使用axios中的写法
    #####一、不要使用下面这种方法【这时候你运行时会发现,数据可以请求到,但是会报错 TypeError: Cannot set property 'listgroup' of undefined 】
    

    axios.get('/user?ID=12345')
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
    console.log(error);
    });

    二、使用这种方法
    

    this.$axios.get(url)
    .then(response => {
    console.log(response.data.subjects);
    this.listarr = response.data.subjects
    console.log(this.listarr);
    })
    .catch(error => {
    console.log(error);
    });

  • 相关阅读:
    jQuery
    jquery操作滚动条滚动到指定元素位置 scrollTop
    javascript的offset、client、scroll使用方法
    js javascript:void(0) 真正含义
    Js中数组Array的用法
    javascript中typeof、undefined 和 null
    函数的参数是函数,函数中Ajax返回的回调函数中的函数运行
    xampp中php手动升级
    jQuery Mobile里xxx怎么用呀? (事件篇)
    eval解析JSON中的注意点
  • 原文地址:https://www.cnblogs.com/lr393993507/p/10027201.html
Copyright © 2020-2023  润新知