时间:2021-03-21 10:31:20 | 栏目:vue | 点击:次
这个例子从 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>