事件的基本使用
- 使用v-on:xxx 或 @xxx 绑定事件,其中xxx是事件名;
- 事件的回调需要配置在methods对象中,最终会在vm上;
- methods中配置的函数,不要用箭头函数!否则this就不是vm了;
- methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象;
- @click="demo" 和 @click="demo($event)" 效果一致,但后者可以传参;
<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">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>事件的基本使用</title>
</head>
<body>
<div id="root">
<h2>欢迎{{name}}学习</h2>
<button v-on:click="showInfo">点我1</button>
<button @click="showInfo">点我2</button>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el: "#root",
data: {
name: "jack"
},
methods: {
showInfo(event) {
console.log(event);
alert(this.name + "同学你好!")
}
}
})
</script>
</body>
</html>