はてなブログの記事を取得してカード表示するVueComponentを作ったので、そのへんの話をメモしておきますm( )m
コードだけ見たい人はこちら👇
はてなブログの記事をカードで表示するVueコンポーネント · GitHub
イメージ
このような形で表示されます🙌
使い方
BlogsコンポーネントのProps
としてendpoint
にrss取得用のurl(https://madogiwa0124.hatenablog.com/rss等)と、displayCount
に表示件数を設定してください。
<Blogs endpoint="https://madogiwa0124.hatenablog.com/rss" displayCount="6" />
カードのデザインを修正したい場合は、BlogCard.vue
のstyle
を変更していただければ👩🎨
実装のはなし
はてなブログの記事を取得する
はてなブログの記事一覧を取得するのは意外と簡単で、ブログURL/rss
でrssフィードを取得できるので、まずはそれを取得します。axios
を使ってリクエストを送信すればOKです👀
import axios from 'axios'; public created() { axios.get(this.endpoint).then((res) => { const rss = res.data }); }
取得した記事をParseする
取得した記事のParseには、DOMParser
を使用しています。RSSもxmlなのでtext/xml
を指定してあげればParse出来ます👀
buildRssBlogItems
でitem(各記事)
を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を使って、いろいろ出来そうですね👀