Madogiwa Blog

主に技術系の学習メモに使っていきます。

はてなブログの記事を取得してカード表示するVueComponentを作った📦✨

はてなブログの記事を取得してカード表示するVueComponentを作ったので、そのへんの話をメモしておきますm( )m

コードだけ見たい人はこちら👇

はてなブログの記事をカードで表示するVueコンポーネント · GitHub

イメージ

このような形で表示されます🙌 f:id:madogiwa0124:20190413193738p:plain

使い方

BlogsコンポーネントPropsとしてendpointrss取得用のurl(https://madogiwa0124.hatenablog.com/rss等)と、displayCountに表示件数を設定してください。

<Blogs
  endpoint="https://madogiwa0124.hatenablog.com/rss"
  displayCount="6"
/>

カードのデザインを修正したい場合は、BlogCard.vuestyleを変更していただければ👩‍🎨

実装のはなし

はてなブログの記事を取得する

はてなブログの記事一覧を取得するのは意外と簡単で、ブログURL/rssrssフィードを取得できるので、まずはそれを取得します。axiosを使ってリクエストを送信すればOKです👀

import axios from 'axios';
public created() {
  axios.get(this.endpoint).then((res)  => { const rss = res.data });
}

取得した記事をParseする

取得した記事のParseには、DOMParserを使用しています。RSSxmlなのでtext/xmlを指定してあげればParse出来ます👀
buildRssBlogItemsitem(各記事)をDocumentにParseしてblogPropsでthumbnail、title、linkを持つobjectを生成してBlogの一覧(blogs)を作成しています🙌

  import axios from 'axios';
  
  public blogs: object[] = [];
  public parser: DOMParser = new DOMParser();

  public created() {
    axios.get(this.endpoint).then((res)  => {
      const rssDom = this.parser.parseFromString(res.data, 'text/xml');
      this.buildRssBlogItems(rssDom);
    });
  }
  private buildRssBlogItems(dom: Document): void {
    dom.querySelectorAll('item').forEach((item) => {
      const itemDom = this.parser.parseFromString(item.innerHTML, 'text/html');
      this.blogs.push(this.blogProps(itemDom));
    });
    this.blogs = this.blogs.slice(0, this.displayCount);
  }
  private blogProps(dom: Document): object  {
    const thumbnail = dom.querySelector('enclosure')!.getAttribute('url');
    const title = dom.querySelector('title')!.text;
    const link = dom.querySelector('body')!.firstChild!.textContent!.trim();
    return { title, thumbnail, link };
  }

おわりに

今回ははてなブログの記事の一覧を表示するVueコンポーネントを作成しました📦
DOMParserを今まであまり使ったことなかったのですが、でHTMLやXMLをParseできるのでスクレイピングの結果やRSSを使って、いろいろ出来そうですね👀