温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue如何获取数据列表展示

发布时间:2020-10-25 19:43:54 来源:脚本之家 阅读:246 作者:我叫白天宇 栏目:web开发

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

一、展示

Vue如何获取数据列表展示

二、源码

<!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.7/dist/vue.js"></script>
</head>
<body>
 <div id="app">
  <h3>title</h3>
  <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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI