前言:
微信小程序中的事件綁定和Vue中的事件綁定其實有很多的相似之處,所以如果有過Vue相關的經驗,學起來的話還是比較容易的。
js代碼:
// 頁面級的js文件必須調用Page函數來注冊頁面, // 否則你的頁面將無法正常渲染 Page({ parent() { console.log('parent') }, father() { console.log('father') }, son() { console.log('son') } })
wxss代碼: (也就是對應的樣式)
.parent{ width: 500rpx; height: 500rpx; background-color: red; margin-bottom: 20rpx; } .father{ width: 300rpx; height: 300rpx; background-color: pink; } .son{ width: 100rpx; height: 100rpx; background-color: yellow; }
wxml代碼:
<!-- bind綁定的事件具有 事件冒泡 --> <view class="parent" bind:tap="parent"> <view class="father" bind:tap="father"> <view class="son" bind:tap="son"></view> </view> </view> <!-- catch綁定的事件會阻止事件的冒泡 --> <view class="parent" catch:tap="parent"> <view class="father" catch:tap="father"> <view class="son" catch:tap="son"></view> </view> </view> <!-- capture-bind 綁定的事件具有 事件捕獲 --> <view class="parent" capture-bind:tap="parent"> <view class="father" capture-bind:tap="father"> <view class="son" capture-bind:tap="son"></view> </view> </view> <!-- capture-catch 綁定的事件會阻止事件捕獲 --> <!-- 但是這樣的話,在內部嵌套的元素永遠無法觸發對應的事件處理函數 --> <view class="parent" capture-catch:tap="parent"> <view class="father" capture-catch:tap="father"> <view class="son" capture-catch:tap="son"></view> </view> </view> <!-- mut-bind綁定的事件具有 互斥效果,即"有我沒你"的感覺 --> <view class="parent" mut-bind:tap="parent"> <view class="father" mut-bind:tap="father"> <view class="son" mut-bind:tap="son"></view> </view> </view>
總結:
- 一般開發中的話用的比較多的是前兩種
- 如果會Vue中的指令的話,入手會很快