【问题标题】:Vue 3, call $emit on variable changeVue 3,在变量更改时调用 $emit
【发布时间】:2021-06-19 12:53:17
【问题描述】:

所以我试图在 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>

【问题讨论】:

    标签: javascript vue.js vue-component vuejs3 vue-composition-api


    【解决方案1】:

    为了保持组件一致,不要在option和composition api之间混用,setup钩子的context参数中可以使用emit函数::

    <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})
              }
    ...
    

    【讨论】:

    猜你喜欢
    • 2022-06-19
    • 2020-04-16
    • 1970-01-01
    • 2020-09-19
    • 2020-04-10
    • 2019-07-01
    • 1970-01-01
    • 2016-01-27
    • 2019-02-14
    相关资源
    最近更新 更多