LoginSignup
1
0

More than 3 years have passed since last update.

Axios / Get

Last updated at Posted at 2021-01-03

本日のゴール

  • axios.get を使えるようになる

アジェンダ

  1. 下準備
  2. import axios
  3. 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()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0