28
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Vue.js】Axiosで取得したAPIデータにリアルタイム検索機能をつけたい

Last updated at Posted at 2019-09-13

APIはこちらを利用させていただいてます。

イメージ

リアルタイム検索.gif

ソースコード

<div id="app">
  <!-- keywordをv-modelで定義することで、inputの内容(=keyword)が変更されるたびにfilterUsers()が実行されます -->
  <input v-model="keyword" placeholder="Search...">
  <ul>
    <!-- keywordが更新されるたびにリストを書き換えたいので、算出プロパティ(computed)を使います。 -->
    <li v-for="user in filteredUsers">
      {{ user.username }}
    </li>
  </ul>
</div>

<script>
const app = new Vue({
    el: '#app',
    data: {
        users: null,
        keyword: '',
    },
    mounted: function() {
        this.getUsers();
    },
    computed: {
        filteredUsers: function () {
            return this.filterUsers();
        }
    },
    methods: {
     // API取得
        getUsers: function () {
            axios.get('https://jsonplaceholder.typicode.com/users')
            .then(res => {
                this.users = res.data
            })
            .catch(err => {
                console.log(err.statusText)
            });
        },
        // keywordに一致するuserを配列に格納し、それを返します
        filterUsers: function () {
            let filtered = [];
            for (let i in this.users) {
                let user = this.users[i];
                if (user.username.indexOf(this.keyword) !== -1) {
                    filtered.push(user);
                }
             }
            return filtered;
        }
    }
});
</script>

デモ

See the Pen Vue + Axios + RealTime Search by nagisa-ito (@nagisa-ito) on CodePen.

28
20
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
28
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?