Programing

Vue 3, 변동 변화에 대해 $emit 호출

c10106 2022. 4. 6. 21:58
반응형

Vue 3, 변동 변화에 대해 $emit 호출

그래서 나는 형태로서의 역할을 하는 Vue 3에 구성 요소를 구축하려고 하는데, 부모가 데이터를 처리하기 위해서는 변경에 관한 모든 입력이 있는 물체를 내보내고 싶다.내가 가지고 있는 문제는 내가 전화를 할 수 없을 것 같다는 것이다.$emit안에서watch()(아마도 컨텍스트 때문이지만, 구성 요소 전체 컨텍스트가 디폴트로 통과되지 않고, 수락되지 않는 이유 또한 알 수 없다.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>

구성 요소의 일관성을 유지하기 위해 옵션과 컴포지션 api를 혼용하지 마십시오.emit에서 사용할 수 있는 기능context의 매개 변수setup후크::

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

참조URL: https://stackoverflow.com/questions/66753488/vue-3-call-emit-on-variable-change

반응형