v-on 监听
<script src="https://how2j.cn/study/vue.min.js"></script> <div id="div1"> <div>一共点击了 {{clickNumber}}次</div> <button v-on:click="count">点击</button> </div> <script> new Vue({ el: '#div1', //获取元素 data: { clickNumber:0 //设置变量 }, methods:{ //新建点击方法 count: function(){ this.clickNumber++; } } }) </script>
v-on:click="count" 可以缩写为@click="count"
事件修饰
.stop ,.prevent,.capture,.self,.once
冒泡事件
<script src="https://how2j.cn/study/vue.min.js"></script> <style type="text/css"> * { margin: 0 auto; text-align:center; line-height: 40px; } div { width: 100px; cursor:pointer; } #grandFather { background: green; } #father { background: blue; } #me { background: red; }#son { background: gray; } </style> <div id="content"> <div id="grandFather" v-on:click="doc"> grandFather <div id="father" v-on:click="doc"> father <div id="me" v-on:click="doc"> me <div id="son" v-on:click="doc"> son </div> </div> </div> </div> </div> <script> var content = new Vue({ el: "#content", data: { id: '' }, methods: { doc: function () { this.id= event.currentTarget.id; alert(this.id) } } }) </script>
父元素里有 子元素, 如果点击了 子元素, 那么click 事件不仅会发生在子元素上,也会发生在其父元素上,依次不停地向父元素冒泡,直到document元素。
stop 停止触发
当使用<div id="me" v-on:click.stop="doc">
冒泡方法执行到此处就会停止 不会执行到父级了
capture 优先触发
<div id="father" v-on:click.capture="doc">
那么当冒泡发生的时候,就会优先让father捕捉事件。
点击capture 内部元素会优先触发
self 自己触发
<div id="father" v-on:click.self="doc">
只有自己点击才会触发
once 只触发一次
<div id="father" v-on:click.once="doc">
如果触发过会跳过
prevent
通过在click后面添加prevent 可以阻止页面刷新
@click.prevent = "jump"
也可以直接,后面不跟函数
@click.prevent
只有超链和form这种会导致页面刷新的操作,.prevent 才有用。 普通的不导致页面刷新的按钮,加上这个没有任何变化。