0
点赞
收藏
分享

微信扫一扫

【Vue】基础系列(五)事件处理-methods配置项-事件的基本使用


和阿牛一起冲Vue


文章目录

  • ​​和阿牛一起冲Vue​​
  • ​​前言​​
  • ​​一、什么是事件​​
  • ​​1、点击事件​​
  • ​​2、v-on:click="showInfo"​​
  • ​​3、参数传入​​
  • ​​简写方式​​
  • ​​参数原理​​
  • ​​二、事件的基本使用​​
  • ​​三、代码总结​​


前言

青春,因为奋斗与奉献更美丽。

一、什么是事件

通俗点讲就是一个行为的交互(一个动作),当点击某个按钮或者触发一个div之类的,产生等等如如何的一个效果……

1、点击事件

当点击某个按钮,触发事件 ​​v-on:click="showInfo"​​(触发一个回调函数)。

<!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>时间处理</title>
</head>

<body>
<div id="root">
<h1>欢迎来到{{message.name}}的世界</h1>
<button v-on:click="showInfo">点我提示信息</button>
</div>

</body>
<script src='vue.js'></script>
<script>.config.productionTip = false;
new Vue({
el: '#root',
data: {
name: 'jack',
message: {
url: 'javascript:void(0)?spm=1000.2115.3001.5343',
name: '勇敢牛牛'
}
},
methods: {
showInfo() {
alert('勇敢牛牛,不怕困难')
}
}
});</script>

</html>

2、v-on:click=“showInfo”

(通过点击触发一个回调函数)

【Vue】基础系列(五)事件处理-methods配置项-事件的基本使用_vue.js


因为Vue是在vue实例中读取内容,我需要在后面配置回调函数对象,因为是在对象当中,不用写​​funtion​​​关键字,直接函数名即可,可以接受参数,但是第一个参数就是​​event​​事件对象。

methods: {
showInfo(event) {
// alert('勇敢牛牛,不怕困难')
console.log(event.target);
}
}

【Vue】基础系列(五)事件处理-methods配置项-事件的基本使用_html_02


要是想拿到事件(按钮对象)的内容:

methods: {
showInfo(event) {
// alert('勇敢牛牛,不怕困难')
console.log(event.target.innerText);
}
}

【Vue】基础系列(五)事件处理-methods配置项-事件的基本使用_vue.js_03

3、参数传入

简写方式

<button @click="showInfo">点我提示信息</button>

参数原理

可以增加元素,但是为了保证event的存在。需要加一个$event占个位

<button @click="showInfo(666,$event)">点我提示信息</button>
^^^^^^^^^
methods: {
showInfo(number) {
// alert('勇敢牛牛,不怕困难')
// console.log(event.target.innerText);
console.log(number);
}
}

注意:函数是不需要数据代理的(这不需改动的)

二、事件的基本使用

1.使用v-on:xxx 或 @xxx 绑定事件,其中xxx是事件名;
2.事件的回调需要配置在methods对象中,最终会在vm上;
3.methods中配置的函数,不要用箭头函数!否则this就不是vm了;
4.methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象;
5.@click=“demo” 和 @click=“demo($event)” 效果一致,但后者可以传参;

三、代码总结

<!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>时间处理</title>
</head>

<body>
<div id="root">
<h1>欢迎来到{{message.name}}的世界</h1>
<!-- <button v-on:click="showInfo">点我提示信息</button> -->
<button @click="showInfo(666,$event)">点我提示信息</button>

</div>

</body>
<script src='vue.js'></script>
<script>.config.productionTip = false;
new Vue({
el: '#root',
data: {
name: 'jack',
message: {
url: 'javascript:void(0)?spm=1000.2115.3001.5343',
name: '勇敢牛牛'
}
},
methods: {
showInfo(number) {
// alert('勇敢牛牛,不怕困难')
// console.log(event.target.innerText);
console.log(number);
}
}
});</script>

</html>


举报

相关推荐

0 条评论