Skip to content

5 - watch 全家桶 #2164

Open
Open
@willow237

Description

@willow237
// 你的答案
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';

const count = ref(0);

/**
 * Challenge 1: Watch once
 * Make sure the watch callback only triggers once
 */
// 当我们想要让watch生效有限次的时候,都需要手动停止它。当一个watch创建的时候,它的返回值就是它的停止方法,直接调用这个方法即可停止watch的监听
const unwatch = watch(count, () => {
  console.log('Only triggered once');
  unwatch();
});

count.value = 1;
setTimeout(() => (count.value = 2));

/**
 * Challenge 2: Watch object
 * Make sure the watch callback is triggered
 */
const state = ref({
  count: 0,
});

watch(
  () => state.value.count,
  () => {
    console.log('The state.count updated');
  },
  { deep: true }
);

state.value.count = 2;

/**
 * Challenge 3: Callback Flush Timing
 * Make sure visited the updated eleRef
 */

const eleRef = ref();
const age = ref(2);
watch(
  age,
  () => {
    console.log(eleRef.value);
  },
  { flush: 'post' }
);
age.value = 18;
</script>

<template>
  <div>
    <p>
      {{ count }}
    </p>
    <p ref="eleRef">
      {{ age }}
    </p>
  </div>
</template>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions