本日のゴール
- axios.get を使えるようになる
アジェンダ
- 下準備
- import axios
- getData の出力
1. 下準備
- html, jsonは下記のように準備
HTML
<ul class="js-AxiosTest">
<!--
// この中にgetしたデータを出力予定
<li>Heading 1<br>text 1</li>
<li>Heading 2<br>text 2</li>
<li>Heading 3<br>text 3</li>
-->
</ul>
json
[{
"title": "Heading 1",
"text": "text 1"
}, {
"title": "Heading 2",
"text": "text 2"
}, {
"title": "Heading 3",
"text": "text 3"
}]
2. import axios
Github
CDN
<script src="https://unpkg.com/axios/dist/axios.min.js" defer></script>
3. getData の出力
class AxiosGet {
constructor(el) {
this.el = el
this.srcHtml = ''
}
async init() {
this.items = await this.getData()
this.srcHtml = this.createHtml(this.items)
this.el.innerHTML = this.srcHtml
}
async getData() {
const { data } = await axios.get('http://localhost:3000/data/index.json') // 取得したいjsonのパスを記載
return data
}
createHtml(items) {
let elements = ''
for (let item of items) {
elements += `
<li>${item.title}<br>${item.text}<li>
`
}
return elements
}
}
const el = document.querySelector('.js-AxiosTest')
new AxiosGet(el).init()