在vue 项目开发中,常常为了,节省代码、高效利用,会封装自定义组件,封装自定义组件,传值就是 prop ,那绑定事件呢?

<!--
 * @Description: 
 * @Author: 呆呆狗
 * @Date: 2021-05-09 10:02:15
 * @LastEditTime: 2021-05-10 09:52:07
 * @LastEditors: 呆呆狗
-->
<template>
  <div>
    点击事件
    <d-button @click="handle">传值</d-button>
  </div>
</template>

<script>
import DButton from "./components/Button/index.vue";
export default {
  methods: {
    handle(e) {
      console.log("点击了", e);
    },
  },
  components: {
    DButton,
  },
};
</script>

假设,前提:d-button 没有绑定事件,父组件是这样写的,你点把,把 button 按钮,点 烂,都不会 有输出结果。

其实,在自定义组件中,你给他加一个 click 事件,vue 会默认认为它是一个自定义事件

正确的写法

父组件

<template>
  <div>
    点击事件
    <d-button @click="handle">传值</d-button>
  </div>
</template>

<script>
import DButton from "./components/Button/index.vue";
export default {
  methods: {
    handle(e) {
      console.log("点击了", e);
    },
  },
  components: {
    DButton,
  },
};
</script>

子组件

<!--
 * @Description: 
 * @Author: 呆呆狗
 * @Date: 2021-05-09 10:06:49
 * @LastEditTime: 2021-05-10 10:07:20
 * @LastEditors: 呆呆狗
-->
<template>
  <button :class="[typeClass, sizeClass]" class="h-btn" @click="clickBtn">
    <slot></slot>
  </button>
</template>

<script>
export default {
  methods: {
    clickBtn(e) {
      // 触发 父组件 传下来的自定义事件  click
      this.$emit("click", e);
    },
  },
  components: {},
};
</script>

在,子组件中,我们是可以 给 button 绑定 click 事件的,因为 原生button 标签,本来就有 click 事件,这里只是巧妙利用了,子传父的一个思想,用 $emit 暴露出去一个自定义事件,父监听,,子组件触发了点击事件,同时,父也会监听到

组件绑定的事件默认是不会被浏览器识别的,我们需要做额外的处理让事件生效,有俩种方案,
1、添加 .native 修饰符,添加了这个修饰符,事件就会绑定到组件的根元素身上
2、把click 当成自定义事件 通过 $emit 执行 (通用写法)

组件绑定的事件,默认是不会被浏览器识别的,我们需要做额外的处理

1.添加 .native 修饰符,添加了这个修饰符,事件就会绑定到组件的根元素身上。但是这种方案,不推荐,会有一定的问题
2. 把click 当成自定义事件 通过 $emit 执行 (通用写法)

事件如果写道原生支持的标签身上,会被直接识别为原生事件 <button @click=handleder>

事件如果写在 自定义组件身上,默认状态会被识别为自定义事件 <d-button @click=“hander1”>

添加 .native 修饰符,可以让 vue 帮助我们把事件绑定成浏览器支持的原生事件
就当成自定义事件识别,然后按照 父子组件 通信的手段,通过子组件内事件触发,然后调用 $emit 方法触发即可。

Logo

前往低代码交流专区

更多推荐