vue.jsとaxiosを使ってjsonのデータを表示

未分類

以下のページを参考にvue.jsとaxiosを使ってjsonのデータを表示點せました。

vue.jsを使ってaxiosを学ぶ | アールエフェクト
vue.jsでajaxリクエストを行う場合は、axiosを使用する機会が非常に多いです。axiosの使用方法は非常にわかりやすいのでマスターするのにも時間がかかりません。また開発に必要なダミーデータもJSONPlaceholderというサービスを使うことができます。

sample_vue.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>sample</title>
</head>
<body>

  <div id="app">
  <input v-model="name"><br>
  <button v-on:click="createNewUser">作成</button>
  <ul>
    <li v-for="user in users">{{ user.name }}</li>
  </ul>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>


  <script language="javascript" type="text/javascript">

    new Vue({
      el: '#app',
      data: {
        users: [],
        name: ''
      },
      methods : {

        createNewUser: function(){
         axios
         .post('https://jsonplaceholder.typicode.com/users',{name: this.name})
         // .then(response => this.users.unshift(response.data))
         // .then(response => this.users.unshift(response.data))

         .then(response => {
             this.users.push(response.data);
         })
         .catch(response => {
             console.log(response)
         })
         console.log(this);
        }
      },

      mounted :function(){
        axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            this.users = response.data
        })
        .catch(response => {
            console.log(response)
        })
      }
    })

  </script>

</body>
</html>

 

コメント

タイトルとURLをコピーしました