亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

自定義組件添加原生事件

在用 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前端工程師
手記
粉絲
8379
獲贊與收藏
109

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消