Blogger Information
Blog 87
fans 1
comment 0
visits 59148
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
vue实战使用ajax请求后台数据
阿杰
Original
2450 people have browsed it

Axios的安装和引入

  1. 使用npm安装:
    1. $npm install axios -S
  2. 在vue项目公共文件(我这里是main.js文件)中引入:
    1. import axios from "axios";
  3. axios跟很多第三方模块不同的一点是它不能直接使用use方法,而是用下面这种方法:
    1. Vue.prototype.$axios = axios;
  4. 这样呢在methods里用到的时候直接用this.$axios来调用它:
    1. this.$axios.get(接口地址).then(function(respon){}).catch(function(error){})

axios.get

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    2. params:{
    3. video_id:4
    4. }
    5. }).then(res=>{
    6. console.log(res);
    7. }).catch(function(error){
    8. })

axios.post

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",{
    2. params:{
    3. token:'050e26b301245052c8ef807677025bb2',
    4. com_id:19792
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })

    会出现跨域问题,因为axios本身并不支持发送跨域的请求

    解决方案:通过字符串的方式发送数据

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",'token=050e26b301245052c8ef807677025bb2&com_id=19792').then(res=>{
    2. console.log(res.data.data);
    3. }).catch(function(error){
    4. })

用qs来解决post跨域问题

  1. 安装qs:
    1. npm install --save axios vue-axios qs
    2. import qs from 'qs' qs 用来解决vue中post请求以 a=a&b=b 的格式
  2. main.js 内容:
    1. import axios from "axios"
    2. import qs from "qs"
    3. Vue.prototype.$axios = axios
    4. Vue.prototype.$qs = qs
  3. 需要的页面请求接口时 get 和post 两种方法:

    1. getbuyer:function(){
    2. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    3. params:{
    4. video_id:4
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })
    10. },
    11. getData:function(){
    12. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",
    13. this.$qs.stringify({
    14. token:'050e26b301245052c8ef807677025bb2',
    15. com_id:19792
    16. })
    17. ).then(res=>{
    18. console.log(res);
    19. }).catch(function(error){
    20. })
    21. }

    请求成功

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post