Vue-CLI项目-axios模块前后端交互(类似ajax提交)

08.31自我总结

Vue-CLI项目-axios前后端交互

一.模块的安装

npm install axios --save
#--save可以不用写

二.配置main.js

import axios from 'axios'
Vue.prototype.$axios = axios;

三.使用

created() {  // 组件创建成功的钩子函数
    // 拿到要访问课程详情的课程id
    let id = this.$route.params.pk || this.$route.query.pk || 1;
    this.$axios({
        url: `http://127.0.0.1:8000/course/detail/${id}/`,  // 后台接口
        method: 'get',  // 请求方式
    }).then(response => {  // 请求成功
        console.log('请求成功');
        console.log(response.data);
        this.course_ctx = response.data;  // 将后台数据赋值给前台变量完成页面渲染
    }).catch(error => {  // 请求失败
        console.log('请求失败');
        console.log(error);
    })
}

与ajax提交不同的一些设置

  • ajax 中的tyle这里是method
  • ajax中的success这里是then且不在大括号内后面接着.出来
  • catch请失败
  • axios可能会用到的参数responseType:'blob'这是让请求的内容返回二进制
posted @ 2019-08-31 21:45  小小咸鱼YwY  阅读(2880)  评论(1编辑  收藏  举报