事件的基本使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="root">
<h1>欢迎学习{{name}}!</h1><br>
<!-- <button v-on:click="showInfo">点我提示信息</button> -->
<button @click="showInfo1">点我提示信息1(不传参)</button>
<button @click="showInfo2($event,66)">点我提示信息2(传参)</button>
</div>
<script>
Vue.config.productionTip = false;
// 事件的基本使用:
// 1.使用v-on:xxx或@xxx绑定事件,xxx是事件名;
// 2.事件的回调需要配置在methods对象中,最终会在vm上面;
// 3.methods中配置的函数不需要用箭头函数,否则this就不是只想vm了;
// 4.methods中配置的函数都是被Vue所管理的函数,this的指向是vm或组件实例对象;
// 5.@click="demo"和@click="demo($event)"效果一致,但后者可以传参
const vm = new Vue({
el: '#root',
data() {
return {
name: 'Vue'
}
},
methods: {
showInfo1() {
alert('你好')
},
showInfo2(event, number) {
console.log(event, number);
}
}
})
</script>
</body>
</html>
事件修饰符:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../lib/vue.js"></script>
<style>
* {
margin-top: 20px;
}
.demo1 {
height: 50px;
background-color: blueviolet;
}
</style>
</head>
<!-- prevent:阻止默认事件
stop:阻止事件冒泡
once:事件只触发一次
captrue:使用事件的捕获模式
self:只有event.target是当前操作的元素时才触发的事件
passive:事件的默认行为立即执行,无需等待事件回调执行完毕 -->
<body>
<div id="root">
<!-- 阻止默认事件 -->
<a href="http://www.atguigu.com" @click.prevent="showInfo($event)">点我提示信息</a>
<!-- 阻止冒泡 -->
<div class="demo1" @click="showInfo">
<button @click.stop="showInfo">点我提示信息</button>
</div>
<!-- 事件只触发一次 -->
<button @click.once="showInfo">点我提示信息</button>
</div>
<script>
const vm = new Vue({
data() {
return {
}
},
methods: {
showInfo(event) {
alert('你好,Vue!')
}
}
});
vm.$mount('#root');
</script>
</body>
</html>