事件冒泡是指事件在触发后,从最深的元素开始逐层向上执行事件处理函数,直到最顶层元素。事件冒泡的好处是可以多次处理一个事件,且易于维护和开发
输入框事件
<el-input :placeholder="titletip" v-model="form.input" @keyup.enter.native="inputkey($event)" clearable size="mini">
<el-button slot="append" icon="el-icon-search" @click="query()">查询</el-button>
<el-button slot="append" icon="el-icon-check" @click="retbtn()" style="font-weight: bold;">确定</el-button>
</el-input>
绑定全局事件
//DOM渲染完成,组件挂载完成
mounted() {
addEventListener('keyup', this.keyUp,false)
},
methods: {
inputkey(e) {
// el-input 回车
console.log('sendMsg', e.keyCode);
e.stopPropagation() // 阻止事件冒泡,不走到keyup
},
keyUp(e) {
console.log('keyUp', e.keyCode);
}
}
methods
和$emit
在子组件中实现了handleClick
方法,并通过$emit('click.stop')
方法来阻止冒泡传递
<template>
<div id="parent" @click="handleParent">
<child @click="handleChild"></child>
</div>
</template>
<script>
export default {
methods: {
handleParent() {
console.log('parent clicked')
},
handleChild() {
console.log('child clicked')
this.$emit('click.stop') // 阻止事件冒泡
}
},
components: {
child: {
template: '<div id="child">点击我</div>',
methods: {
handleClick() {
console.log('child clicked')
this.$emit('click.stop') // 阻止事件冒泡
}
}
}
}
}
</script>
除了使用@click.stop
等修饰符来阻止事件冒泡外,我们还可以使用Vue提供的指令v-on:click.stop
来阻止事件冒泡
v-on:click.stop.prevent
指令的作用与@click.stop.prevent
修饰符相同
<template>
<div v-on:click.stop.prevent="handleDivClick">
<button type="submit" @click="handleBtnClick">阻止默认事件</button>
</div>
</template>
<script>
export default {
methods: {
handleDivClick() {
console.log('click')
},
handleBtnClick() {
console.log('submit')
}
}
}
</script>