Search code examples
nuxt.jsvuejs3vue-composition-apinuxt3.jsvueuse

(Vue 3, Nuxt 3) The value from the child component to parent component emits only after adding changes in vs code


I need to emit the height value from the СhildСomponent into the pages/index component in the puzzleSelectBlockHeight ref. But the problem is that this only happens after I change something in the index.vue component like change text or adding/removing divs. Please tell me why this happens and how to fix it?

Demo: https://codesandbox.io/p/sandbox/test-2-zh3g8r?file=%2Fpages%2Findex.vue%3A11%2C20

https://zh3g8r-3000.csb.app/


Solution

  • Use a watcher instead of the onMounted hook. It will be able to emit the new height any time it changes. I'd also suggest emitting the inner ref value rather than the ref itself, since reactivity across components won't work. The watcher will still make sure the newest height value is always emitted.

    ChildComponent.vue

    function blockHeight() {
      emit('block-height', height.value)
      console.log('height', height.value)
    }
    
    watch(height, () => {
        blockHeight()
      },
      { immediate: true }
    )