为了账号安全,请及时绑定邮箱和手机立即绑定

自定义组件添加原生事件

在用 vue 做开发时,新手们肯定会遇到这种问题,直接使用 button 添加原生事件是没有问题的,但是使用自定义组件添加原生事件时,就会发现添加不上。比如我写了两个 button,一个点击让 div 变红,一个点击让 div 变蓝。

App.vue文件

<template>
  <div id="app">
    <button @click="changeRed">变红</button>
    <!-- 使用 Btn 组件  并添加原生事件 -->
    <Btn @click="changeBlue"></Btn>
    <div :class="box"></div>
  </div></template><script>// 引入 Btn 这个组件import Btn from './assets/components/Btn.vue'export default {  name: 'app',
  data () {    return {      box: 'yellow'
    }
  },  methods: {
    changeRed(){      this.box = 'red'
    },
    changeBlue(){      this.box = 'blue'
    }
  },  // 组件 注册
  components: {
    Btn
  }
}</script><style>.yellow{  width: 200px;  height: 200px;  background: #ff0;
}.red{  width: 200px;  height: 200px;  background: #f00;
}.blue{  width: 200px;  height: 200px;  background: #00f;
}</style>

Btn.vue 文件

<template>
    <div class="btn">
        <button>变蓝</button>
    </div></template>


343

点击变色.gif


会发现 Btn 的绑定事件无效。其实 vue 官方是有提供对应的方法的, 给组件绑定原生事件,就是在自定义组件 Btn 的原生事件后面加个 .native 后缀就好了。


App.vue文件

<template>
  <div id="app">
    <button @click="changeRed">变红</button>
    <!-- 使用 Btn 组件  并添加事件 -->
    <Btn @click.native="changeBlue"></Btn>
    <div :class="box"></div>
  </div></template>

效果:


343

点击变色-1.gif



点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
8381
获赞与收藏
109

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消