Vue.native如何將原生事件綁定到組件
.native將原生事件綁定到組件
詳見vue官網(wǎng)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>Vue .native 將原生事件綁定到組件</title> </head> <body> <div id="swq"> <!----> <swq @click="clickSwq">在組件上 @click 無效</swq> <swq @click.native="clickSwq">要在組件上綁定事件, 需使用 native, @click.native</swq> <!----> </div> <script type="text/x-template" id="swq-template"> <div> <slot></slot> </div> </script> <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script> <script type="text/javascript"> var swq = { template: "#swq-template", }; var vu = new Vue({ el: "#swq", methods: { clickSwq() { console.log("點擊了<swq />") } }, components: { swq: swq, }, }) </script> </body> </html>
vue事件中的.native
.native是什么?
.native - 監(jiān)聽組件根元素的原生事件。
主要是給自定義的組件添加原生事件。
例子
給普通的標(biāo)簽加事件,然后加native是無效的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="app"> <button @click.native="clickFn">按鈕</button> </div> <script src='vue.js'></script> <script> new Vue({ el:'#app', data:{ }, methods:{ clickFn () { console.log('點擊按鈕了') } } }) </script> </body> </html>
onclick事件不會觸發(fā)!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="app"> <card @click.native="clickFn">按鈕</card> </div> <script src='vue.js'></script> <script> Vue.component('card',{ template:'<p>這是card組件<button>按鈕</button></p>' }) new Vue({ el:'#app', data:{ state:false }, methods:{ clickFn (e) { console.log(e) //打印出MouseEvent對象 if (e.target.nodeName === 'IMG') { // 可以對點擊的target標(biāo)簽進(jìn)行判斷 this.dialogImageUrl = file.target.src this.dialogVisible = true } } } }) </script> </body> </html>
心得:
.native - 主要是給自定義的組件添加原生事件。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue預(yù)覽本地pdf文件方法之vue-pdf組件使用
這篇文章主要介紹了vue預(yù)覽本地pdf文件方法之vue-pdf組件使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03vue3 Teleport瞬間移動函數(shù)使用方法詳解
這篇文章主要為大家詳細(xì)介紹了vue3 Teleport瞬間移動函數(shù)使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-03-03Vue3實戰(zhàn)學(xué)習(xí)配置使用vue?router路由步驟示例
這篇文章主要為大家介紹了Vue3實戰(zhàn)學(xué)習(xí)配置使用vue?router路由步驟示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06vue select二級聯(lián)動第二級默認(rèn)選中第一個option值的實例
下面小編就為大家分享一篇vue select二級聯(lián)動第二級默認(rèn)選中第一個option值的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01淺談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法
下面小編就為大家?guī)硪黄獪\談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09