Subscribe on changes!

Immediate and post priority issues

avatar
Nov 30th 2021

Version

3.2.22

Reproduction link

codesandbox.io

Steps to reproduce

console.log:

  • default immediate: true | null
  • click button: false | null
  • click button: true | showRef
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'

export default defineComponent({
  setup() {
    const show = ref(true)
    const showRef = ref<HTMLDivElement | null>(null)

    watch(
      show,
      (val) => {
        console.log(val)
        console.log(showRef.value)
      },
      { immediate: true, flush: 'post' },
    )

    const toggleShow = () => {
      show.value = !show.value
    }

    return {
      show,
      showRef,
      toggleShow,
    }
  },
})
</script>

<template>
  <div v-if="show" ref="showRef">this is content</div>
  <button @click="toggleShow">toggle</button>
</template>

What is expected?

You can get the dom

What is actually happening?

dom is null

avatar
Nov 30th 2021

It is null because it runs immediately too thanks to { immediate: true, flush: 'post' }

avatar
Nov 30th 2021

immediate Is the callback executed immediately, or is the callback registered immediately?

avatar
Dec 10th 2021

I see, that's why watchPostEffect is needed, watchPostEffect is not just shorthand for Api