0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Vue] ウォッチャー

0
Posted at

引き続きVue公式サイトのチュートリアルの勉強です。
ウォッチャー。

上記、公式サイトに書いてある例、

import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newCount) => {
  // そう、console.log() は副作用です
  console.log(`new count is: ${newCount}`)
})

watchの、
第1引数のcount が 監視対象で、
第2引数がコールバック関数。
監視対象のcount が変更されたら、例で言うところの副作用console.log()が呼ばれる。

watch は3つの引数を取ります。
監視対象 (Source): ref、reactive オブジェクト、ゲッター関数、またはそれらの配列。
コールバック関数 (Callback): データが変更されたときに実行される処理。新しい値と古い値を受け取れます。
オプション (Options): 監視の挙動を調整するためのオブジェクト(任意)。

初めのコード。watchしてない状態。

vue
<script setup>
import { ref } from 'vue';

const todoId = ref(1);
const todoData = ref(null);

async function fetchData() {
  todoData.value = null;
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${todoId.value}`
  );
  todoData.value = await res.json();
}

fetchData();
</script>

<template>
  <p>Todo id: {{ todoId }}</p>
  <button @click="todoId++" :disabled="!todoData">Fetch next todo</button>
  <p v-if="!todoData">Loading...</p>
  <pre v-else>{{ todoData }}</pre>
</template>

<style></style>

この状況だと、ボタンを押しても、todoId が増えていくだけ。

stackblitz 埋め込み。

watchを使う。

単にこの1行を入れるだけでよいっぽい。

watch(todoId, fetchData)

todoId を監視対象として、データ変更があったら、fetchData関数を呼ぶ。

  1. ボタンを押したら、todoIdが変更される。
  2. watchによって、todoIdが変更されたら、fetchDataが呼ばれる。
  3. fetchDataの中では、新しいjsonレスポンスを、todoData.valueにセットしている。

stackblitz 埋め込み。

fetchして新しいデータ取得するまでに少し時間がかかるが、
その間はLoading...のテキストが表示されるようになっている。

このコードで、todoDataが空(null)の場合は、Loading...のテキストを表示している。

  <p v-if="!todoData">Loading...</p>
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?