Vue 3,在变量更改时调用 $emit

Vue 3, call $emit on variable change

所以我正在尝试在 Vue 3 中构建一个组件作为一个表单,为了让父级处理数据,我希望它发出一个包含所有输入变化的对象。我遇到的问题是我似乎无法从 watch() 中调用 $emit (可能是因为上下文,但我也不明白为什么组件范围的上下文默认情况下不通过,并且不接受 this)。由于同样的原因,我也无法调用任何方法。

我确实看到有些人使用 watch: {} 语法,但据我所知,它已被弃用,对我来说也没有多大意义。

这是我正在努力完成的一个最小示例。每当输入日期更改时,我希望组件发出自定义事件。

<template>
  <input
    v-model="date"
    name="dateInput"
    type="date"
  >
</template>

<script>
import { watch, ref } from "vue";

    export default {
        name: 'Demo',
        props: {
        },
        emits: ["date-updated"],
        setup() {
          const date = ref("")

          watch([date], (newVal) => {
            // $emit is undefined
            console.log(newVal);
            $emit("date-updated", {newVal})
            // watchHandler is undefined
            watchHandler(newVal)
          })

          return {
            date
          }
        },
        data() {
            return {
            }
        },
        mounted() {
        },
        methods: {
          watchHandler(newVal) {
            console.log(newVal);
            $emit("date-updated", {newVal})
          }
        },
    }
</script>

不要混用option和composition api为了保持组件的一致性,emit函数在setupcontext参数中可用挂钩::

<template>
  <input
    v-model="date"
    name="dateInput"
    type="date"
  >
</template>

<script>
import { watch, ref } from "vue";
export default {
        name: 'Demo',
        props: {},
        emits: ["date-updated"],
        setup(props,context) {// or setup(props,{emit}) then use emit directly
          const date = ref("")

          watch(date, (newVal) => {
            context.emit("date-updated", {newVal}) 
          })

          return {
            date
          }
        },  
    }
</script>

如果你想添加方法 watchHandler 你可以将它定义为一个简单的 js 函数,如 :

...
 watch(date, (newVal) => {
            context.emit("date-updated", {newVal}) 
          })

  function watchHandler(newVal) {
            console.log(newVal);
           context.emit("date-updated", {newVal})
          }
...