axios模块封装和分类列表实现

这个作用 主要还是为了让代码更加的,清晰。 不要全部都放到  created(){}  这个方法下面。
把这些代码全部抽离出去。 这里就只是去调用方法。
1. src 目录下,新建文件夹---  restful 文件夹下面新建js文件: api.js

import Axios from 'axios' // 导入axios    下载npm install axios -S
Axios.defaults.baseURL = 'https://www.luffycity.com/api/v1/'; // 设置公共URL

// 获取课程分类列表 Api
export const categoryList = ()=> {
  return Axios.get('course_sub/category/list/')  // 返回出去一个 Axios 实例对象
    .then(res=> res.data)// 把接受到的数据也 返回出. 这里不要加 {} 。俺也不知道为啥,你加了。就拿不到结果
    .catch(err=>{})// 这里不知道有啥用
};

// courses/?sub_category=0&ordering= 获取所有课程的api
export const allCourseList = (query_id)=> {
  return Axios.get(`courses/?sub_category=${query_id}&ordering=`) // 使用 `` 并用 ${} 拼接字符串

    .then(res=> res.data)
    .catch(err=>{})
};

在这个里面去写去请求数据的逻辑,然后将 Axios 这个对象返回出去。

抛出 两个方法。其他任何组建,再用的时候直接调用就好了。


2.  在main.js 里面, 将这个写好的  api.js  里面所有的东西。挂载到Vue。 这样组件才可以调用。

import Vue from 'vue'
import App from './App'
import router from './router/index'
import ElementUI from 'element-ui'  // element-ui 导入
import 'element-ui/lib/theme-chalk/index.css' // 导入element-ui的样式
import '../static/globle/globle.css'  // 导入自己写的样式

import Axios from 'axios' // 导入axios    下载npm install axios -S
Vue.prototype.$axios = Axios; // 挂载 axios  这里不能使用 use 的挂载方式

import * as api from './restful/api.js'  // 在这里引入写好的API
Vue.prototype.$http = api;  // 然后就可以在各个组件中,使用 $http.xxx 去调用想用的api函数了

Vue.config.productionTip = false;  // 这个没啥用
Vue.use(ElementUI);  // 挂载 element-ui


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,  // 挂载路由
  template: '<App/>',
  components: { App },
});

这里给这个 导入的api 对象。挂载到 Vue时, 起了个别名  $http  . 就更清楚了。

3. 到免费课程的 Vue组件中 里面,使用里面的方法。

<script>
  export default {
    name: 'FreeCourse',
    data() {
      return {
        categoryList: [],// 分类列表
        currentIndex: 0,//分类列表默认选中(使用的v-bind绑定类, 根据当前的这个值判断 true or false 是否添加active类名。展现样式)
        categoryId: 0,//为0 就代表。获取包含所有的课程的列表
      }
    },

    methods: {
      courseClick(index, id) {
        this.currentIndex = index;//修改分类列表的样式
        this.categoryId = id;
        this.getAllCourseList();
      },

      // 获取分类列表
      getCategoryList() {
        // 返回一个Axios实例化对象. 所以可以使用 res 进行取值
        this.$http.categoryList()
          .then(res => {
            if (!res.error_no) {
              this.categoryList = res.data;
              let category = {  //往列表里添加一个字典. 这个渲染到前端添加一个全部的按钮。用于展示全部课程
                id: 0,
                category: 0,
                name: '全部'
              };
              this.categoryList.unshift(category) // unshift 插入到数组的第一个位置上
            }
          })
          .catch(err => {
            console.log(err);
          });
      },

      // 获取全部的课程列表
      getAllCourseList() {
        this.$http.allCourseList(this.categoryId)
          .then(res => {
            if (!res.error_no) {
              this.courseDetail = res.data;
            }
          }).catch(err => {})
      },
    },

    // 生命周期  在created方法发起ajax请求
    created() {
      this.getCategoryList();  // 调用外面写的方法。 这里就不会显得太臃肿了
      this.getAllCourseList();
    }
  };

</script>

这里的数据 根据从后端请求到的,数据格式来。
要发起 ajax 请求, 肯定要在请求周期的  created() 钩子函数中。

两个方法,一个是用来获取,课程 分类列表的。 一个是用来获取课程列表的。 两个方法都写在 methods 里面。
methods 里面去调用 $http.xxx  获取数据。 并且更新到 data(){} 里面。
有于 数据驱动视图, 使用 v-for v-if 这种就可以, 刷新出不同的数据了。

原文地址:https://www.cnblogs.com/chengege/p/10947409.html