在 UniApp 中,点击事件主要通过 @click 或 v-on:click 指令实现,适用于页面元素(如按钮、视图等)。以下是具体方法:
1. 基础点击事件
在模板中使用 @click 绑定方法:
<button @click="handleClick">点击我</button>
<view @click="tapView">点击视图</view>
在脚本中定义方法:
export default {
methods: {
handleClick() {
console.log('按钮被点击');
uni.showToast({ title: '按钮点击' });
},
tapView() {
uni.navigateTo({ url: '/pages/detail/detail' }); // 跳转页面示例
}
}
}
2. 传递参数
使用内联箭头函数或 data- 属性传递参数:
<button @click="() => handleWithParam('hello')">传递参数</button>
<view data-id="123" @click="handleDataClick">Data参数</view>
脚本中接收参数:
methods: {
handleWithParam(msg) {
console.log('参数:', msg); // 输出: hello
},
handleDataClick(event) {
const id = event.currentTarget.dataset.id; // 获取 data-id
console.log('ID:', id); // 输出: 123
}
}
3. 阻止事件冒泡
使用 @tap.stop(推荐)或原生 event.stopPropagation():
<view @click="parentClick">
<button @tap.stop="childClick">阻止冒泡</button>
</view>
4. 注意事项
- 兼容性:
@click 在 UniApp 中已优化,支持各端(H5、小程序、App)。
- 性能:避免在模板内编写复杂逻辑,尽量调用方法。
- 小程序中部分组件(如
scroll-view)需使用特定事件,如 @tap。
示例场景
<template>
<view>
<button @click="submitForm">提交</button>
<text @click="changeText">{{ message }}</text>
</view>
</template>
<script>
export default {
data() {
return { message: '点击修改文字' };
},
methods: {
submitForm() {
uni.request({ url: 'https://api.example.com/submit', method: 'POST' });
},
changeText() {
this.message = '文字已更新!';
}
}
}
</script>
通过以上方法,可灵活处理点击交互。如有复杂需求(如长按、双击),可结合 @longpress 或自定义手势库。