- 使用v-on:xxx或@xxx绑定事件,其中xxx是事件名
- 事件的回调需要配置在methods对象中,最终会在vm上
- methods中配置的函数,,不要用箭头函数,否则this就不是vm了
- methods中配置的函数都是被vue所管理的函数,this的指向是vm或组件实例对象
- @click="demo"和@click="demo($event)"效果一致,但后者可以传参
<div id="root">
<button v-on:click="show">点我</button>
<!--
<button @click="showInfo(66,$event)">点我传参</button>
</div>
<script type="text/javascript">
Vue.config.productionTip=false
new Vue({
el:'#root',
data: {
name:'word',
},
methods:{
show(event){
alert("你好")
},
showInfo(number,event){
alert(number)
}
}
})
事件修饰符
- .prevent:阻止默认事件(常用)
- .stop阻止事件冒泡(常用)
- .once:事件只触发一次(常用)
- .capture:使用事件的捕获模式
- .self:只有event.target是当前操作的元素时才触发事件(只执行被操作对象所绑定的事件)
- .passive:事件的默认行为立即执行,无需等待事件回调执行完毕
<style>
* {
margin-top: 20px;
}
.dome1 {
background-color: rgb(70, 178, 211);
height: 50px;
}
.box1{
padding: 5px;
background-color: rgb(145, 200, 44);
}
.box2{
background-color: rgb(234, 22, 22);
}
ul{
width: 200px;
height: 200px;
overflow: auto;
background-color: rgb(22, 36, 233);
}
ul>li{
height: 100px;
}
</style>
</head>
<body>
<div id="root">
<a href="http://www.baidu.com" @click.prevent="showInfo">点击</a>
<div class="dome1" @click="showInfo">
<button @click.stop="showInfo">点我提示信息</button>
</div>
<button @click.once="showInfo">点击提示</button>
<div class="box1" @click.capture="showMsg(1)">
div1
<div class="box2" @click="showMsg(2)">div2</div>
</div>
<div class="dome1" @click.self="showInfo">
<button @click="showInfo">点我提示信息</button>
</div>
<ul @wheel.passive="demo">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<script>
Vue.config.productionTip = false
const vm = new Vue({
el: '#root',
data: {
name: 'word',
},
methods: {
showInfo(e) {
console.log(e.target)
},
showMsg(msg){
alert(msg)
},
demo(){
for(let i=0;i<100;i++){
console.log("#")
}
}
}
})
</script>