Vue CLI项目如何使用axios模块进行前后端交互

这篇文章将为大家详细讲解有关Vue CLI项目如何使用axios模块进行前后端交互,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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这里是them且不在大括号内后面接着.出来

  • catch请失败

  • 内容是在$axios之前

关于“Vue CLI项目如何使用axios模块进行前后端交互”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。