Vue如何获取数据列表展示

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue如何获取数据列表展示

我叫白天宇   2020-05-17 我要评论

这个例子从 Github 的 API 中获取了最新的 Vue.js 提交数据,并且以列表形式将它们展示了出来。你可以轻松地切换 master 和 dev 分支。

一、展示

二、源码

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.7https://img.qb5200.com/download-x/dist/vue.js"></script>
</head>
<body>
 <div id="app">
  <h2>title</h2>
  <template v-for="(branch, index) in branches">
   <input type="radio" 
    :id=index 
    :value="branch" 
    v-model="currentBranch"
   />
   <label :for="index">{{ branch }}</label>
  </template>
  <div>当前选定:{{ currentBranch }}</div>
  <ul>
   <li v-for="item in getData">
    <a :href="item.html_url" rel="external nofollow" >{{ item.sha.slice(0, 7) }}</a>
    - <span>{{ item.commit.message }}</span><br/>
    <span>创建人:<a :href="item.author.html_url" > {{ item.commit.author.name }}</a></span><br/>
    <span>创建时间:{{ item.commit.author.date | formatDate }}</span>
   </li>
  </ul>
 </div>

 <script>
  let apiURL = 'https://api.github.com/repos/vuejs/vue/commits?per_page=3&sha='
  let vm = new Vue({
   el: '#app',
   data() {
    return ({
     branches: ['master', 'dev'],
     currentBranch: 'master',
     getData: null,   
    });
   },
   created() {
    this.fetchDate();
   },
   watch: {
    currentBranch: 'fetchDate'
   },
   filters: {
    formatDate(v) {
     return v.replace(/T|Z/g, ' ');
    }
   },
   methods: {
    fetchDate() {
     var xhr;
     if(window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
     }else {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
     let self = this;
     
     xhr.onload = function() {
      if(xhr.readyState == 4) {
       if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
        self.getData = JSON.parse(xhr.responseText);
       }else {
        console.error(xhr.status, xhr.statusText);
       }
      }
     }
     xhr.open('GET', apiURL + this.currentBranch);
     xhr.send(null);
    }
   },
  });
 </script>
</body>
</html>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们