Vue3.0新特性----emits选项

2021-03-11  本文已影响0人  有一种感动叫做丶只有你懂

emits

我们看一下带校验不带校验的emit事件一个例子

子组件Emiter.vue

<template>
  <button @click="handleClick">点击emit-click事件</button>
  <button @click="handleOpen">点击emit-open事件</button>
</template>
<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
  emits: {
    click: null,//click事件没有检验
    open: (value) => {
      if (typeof value === "string") {
        return true;
      } else {
        return false;
      }
    },
  },
  setup(props, {emit}) {
    const handleClick = function() {
      emit("click");
    };
    const handleOpen = function() {
      emit("open", 1);
    };
    return {
      handleClick,
      handleOpen,
    };
  },
  data() {
    return {};
  },
  methods: {},
});
</script>
<style scoped></style>

父组件Emit.vue

<template>
  <emiter @click="onClick" @open="onOpen"></emiter>
</template>
<script lang="ts">
import {defineComponent} from "vue";
import Emiter from "@/components/Emiter.vue";
export default defineComponent({
  components: {
    Emiter,
  },
  data() {
    return {};
  },
  methods: {
    onClick() {
      console.log("click me!");
    },
    onOpen() {
      console.log("open me!");
    },
  },
});
</script>
<style scoped></style>
看一下结果,控制台输出警告信息
image.png
上一篇 下一篇

猜你喜欢

热点阅读