2.9.2 获取数据

这一节我们将使用代码发起一次http请求获取数据,具体细节可以留待后面,先从宏观操作。
首先定义数据,增加students数组:
  data() {
    return {
      username: "中二之魂",
      message: "正在加载中",
      html: '<a href="https://www.codessp.cn">学习平台</a>',
      textValue: '一个值',
      students:[]  
    };
  },
现在它是空的。然后添加onMounted函数,这个函数会自动被vue调用,简单地说,当页面初始化的时候会调用此函数。现在script部分的所有代码如下
import HelloWorld from '@/components/HelloWorld.vue'
import axios from "axios";
export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  data() {
    return {
      username: "中二之魂",
      message: "正在加载中",
      html: '<a href="https://www.codessp.cn">学习平台</a>',
      textValue: '一个值',
      chapterStudies:[]  
    };
  },
  mounted:function(){
    let url="https://www.codessp.cn/api/queryStudentsStatistic?chapterId=766&classId=68&courseId=31";
    axios({
        headers:{
            "Content-Type":"application/x-www-form-urlencoded",
        },
        method:"get",
        url:url,
        params:''
    }).then((response)=>{
        let data = response.data.data;
        this.chapterStudies = data.chapterStudies;
    });
  }
}
增加了一个新模块axios,它专门负责发起http请求,在后面章节会详细解说。这里只需要知道,axios向第20行的url发起请求,获得数据后处理了赋给了chapterStudies变量(第31行)
这个是json格式解析器网站 https://www.json.cn/,方便我们解析json

最后数据出来了,但样式很难看:
接下来我们稍微修改一下它的外观,在最后的style,加上下面的css:
/*
 表格填充5像素 
 */
td{
      padding:5px;
}
/*
 偶数行背景灰色 
 */
tr:nth-child(even) {
      background: #ccc;
}
/*
 表格宽度1000像素 
 */
table{
      width:1000px;
}