uni-app 的 事件處理器
幾乎全支持 Vue官方文檔:事件處理器
// 事件映射表,左側爲 WEB 事件,右側爲 ``uni-app`` 對應事件
{
click: 'tap',
touchstart: 'touchstart',
touchmove: 'touchmove',
touchcancel: 'touchcancel',
touchend: 'touchend',
tap: 'tap',
longtap: 'longtap', //推薦使用longpress代替
input: 'input',
change: 'change',
submit: 'submit',
blur: 'blur',
focus: 'focus',
reset: 'reset',
confirm: 'confirm',
columnchange: 'columnchange',
linechange: 'linechange',
error: 'error',
scrolltoupper: 'scrolltoupper',
scrolltolower: 'scrolltolower',
scroll: 'scroll'
}
注意:
- 爲兼容各端,事件需使用
v-on
或@
的方式綁定,請勿使用小程序端的bind
和catch
進行事件綁定。 - 事件修飾符
.stop
:各平臺均支持, 使用時會阻止事件冒泡,在非 H5 端同時也會阻止事件的默認行爲.prevent
僅在 H5 平臺支持.self
:僅在 H5 平臺支持.once
:僅在 H5 平臺支持.capture
:僅在 H5 平臺支持.passive
:僅在 H5 平臺支持
- 若需要禁止蒙版下的頁面滾動,可使用
@touchmove.stop.prevent="moveHandle"
,moveHandle 可以用來處理 touchmove 的事件,也可以是一個空函數。 -
<view class="mask" @touchmove.stop.prevent="moveHandle"></view>
按鍵修飾符:
uni-app
運行在手機端,沒有鍵盤事件,所以不支持按鍵修飾符。
在 input 和 textarea 中 change 事件會被轉爲 blur 事件。
踩坑注意:
上列表中沒有的原生事件也可以使用,例如map組件的regionchange 事件直接在組件上寫成 @regionchange,同時這個事件也非常特殊,它的 event type 有 begin 和 end 兩個,導致我們無法在handleProxy 中區分到底是什麼事件,所以你在監聽此類事件的時候同時監聽事件名和事件類型既 <map @regiοnchange="functionName" @end="functionName" @begin="functionName"><map>
平臺差異所致,bind 和 catch 事件同時綁定時候,只會觸發 bind ,catch 不會被觸發,要避免踩坑。
事件修飾符
stop 的使用會阻止冒泡,但是同時綁定了一個非冒泡事件,會導致該元素上的 catchEventName 失效!
prevent 可以直接幹掉,因爲uni-app裏沒有什麼默認事件,比如 submit 並不會跳轉頁面
self 沒有可以判斷的標識
once 也不能做,因爲uni-app沒有 removeEventListener, 雖然可以直接在 handleProxy 中處理,但非常的不優雅,違背了原意,暫不考慮
事件綁定 @click
<template>
<view class="demo" @click="clickTest" @longtap="longtap"></view>
</template>
<script>
export default {
methods:{
clickTest: function(e){
console.log(e);
console.log('click');
},
longtap: function(e){
console.log(e);
console.log('longtap');
}
}
}
</script>
<style>
.demo{width:500px; margin:50px auto; background:#8F8F90; height:500px;}
</style>
注意在小程序中觀察對應事件對象,可以利用此對象獲取更多信息。
事件傳參(動態參數演示)
<template>
<view>
<view v-for="(item, index) in students" class="persons" @click="menuClick" v-bind:id="index">{{index}} - {{item.name}}</view>
</view>
</template>
<script>
export default {
data: {
students : [
{name : "張三", age : 18},
{name : "李四", age : 20}
]
},
methods:{
menuClick : function(e){
console.log(e);
console.log(e.target.id);
}
},
}
</script>
<style>
.persons{width:750px; line-height:2.2em;}
</style>