默认冒泡
默认情况下, js 的事件会向上冒泡, 如: 以下三个 div 元素:
- <div class="grandfather" @click="catchGrandfather">
- <div class="father" @click="catchFather">
- <div class="son" @click="catchSon"></div>
- </div>
- </div>
当我们点击里层的 div, 会触发外层的 div 事件
- let vm = new vue({
- el: "#app",
- data: {
- },
- methods: {
- catchSon() {
- console.log('我还小, 别抓我啊...');
- },
- catchFather() {
- console.log('我上有老, 下有小, 各位官爷, 手下留情啊...');
- },
- catchGrandfather() {
- console.log('你们这些兔崽子, 敢动我这把老骨头试下!');
- }
- }
- })
具体代码 https://gitee.com/zhiqiexing/vue.js/blob/34815855f5770edff751b0890e7e856341704c79/code/01/06.html
冒泡. gif
事件修饰符
vue 提供了事件修饰符, 可以修改默认的事件触发机制:
.stop 阻止冒泡
.prevent 阻止默认事件
.capture 添加事件侦听器时使用事件捕获模式
.self 只当事件在该元素本身 (比如不是子元素) 触发时触发回调
.once 事件只触发一次
以 .stop 为例:
- <div class="grandfather" @click="catchGrandfather">
- <div class="father" @click="catchFather">
- <!-- 阻止此元素向上冒泡 -->
- <div class="son" @click.stop="catchSon"></div>
- </div>
- </div>
阻止冒泡. gif
来源: http://www.jianshu.com/p/484bfc98e7ff