2. 获取GitHub上 Vue.js 提交数据

124 阅读1分钟

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

1.gif

<!DOCTYPE html>
<html>
  <head>
    <title>GitHub Commits</title>
    <script src="https://unpkg.com/vue@2"></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
  </head>
  <body>
    <div id="demo">
      <h1>Latest Vue.js Commits</h1>
      <template v-for="branch in branches">
        <input
          type="radio"
          :id="branch"
          :value="branch"
          name="branch"
          v-model="currentBranch"
        />
        <label :for="branch">{{ branch }}</label>
      </template>
      <p>vuejs/vue@{{ currentBranch }}</p>
      <ul>
        <li v-for="record in commits">
          <a :href="record.html_url" target="_blank" class="commit"
            >{{ record.sha.slice(0, 7) }}</a
          >
          - <span class="message">{{ record.commit.message | truncate }}</span
          ><br />
          by
          <span class="author"
            ><a :href="record.author.html_url" target="_blank"
              >{{ record.commit.author.name }}</a
            ></span
          >
          at
          <span class="date">{{ record.commit.author.date | formatDate }}</span>
        </li>
      </ul>
    </div>

    <script>
      var apiURL =
        "https://api.github.com/repos/vuejs/vue/commits?per_page=3&sha=";

      /**
       * Actual demo
       */

      var demo = new Vue({
        el: "#demo",

        data: {
          branches: ["master", "dev"],
          currentBranch: "master",
          commits: null
        },

        created: function() {
          this.fetchData();
        },

        watch: {
          currentBranch: "fetchData"
        },

        filters: {
          truncate: function(v) {
            var newline = v.indexOf("\n");
            return newline > 0 ? v.slice(0, newline) : v;
          },
          formatDate: function(v) {
            return v.replace(/T|Z/g, " ");
          }
        },

        methods: {
          fetchData: function() {
            var xhr = new XMLHttpRequest();
            var self = this;
            xhr.open("GET", apiURL + self.currentBranch);
            xhr.onload = function() {
              self.commits = JSON.parse(xhr.responseText);
              console.log(self.commits[0].html_url);
            };
            xhr.send();
          }
        }
      });
    </script>
  </body>
</html>

/* ./style.css */
#demo {
  font-family: "Helvetica", Arial, sans-serif;
}
a {
  text-decoration: none;
  color: #f66;
}
li {
  line-height: 1.5em;
  margin-bottom: 20px;
}
.author,
.date {
  font-weight: bold;
}