当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Vue如何获取数据列表展示

Vue如何获取数据列表展示

2020年03月09日  | 移动技术网IT编程  | 我要评论

这个例子从 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.7/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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网