1,事件的基本使用
1.使用v-on:xxx或 @xxx 绑定事件,其中xxx是事件名2.事件的回调需要配置在methods对象中,最终会在vm上3.methods中配置的所数,不要用箭头函数!否则this就不是vm了4.methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象5.@click="demo”和 @click="demo($event)”效果一致,但后者可以传参
< title> 事件的基本使用</ title>
< script src = " ../js/vue.js" > </ script>
< body>
< div id = " root" >
< h1> 您好,{{name}}</ h1>
< button @click = " showInfo" > 点我提示信息(不传参)</ button>
< button @click = " showInfo2(66,$event)" > 点我提示信息2(传参)</ button>
</ div>
</ body>
< script type = " text/javascript" >
const vm = new Vue ( {
el: '#root' ,
data: {
name: '张三'
methods : {
showInfo ( e ) { console. log ( e) ; console. log ( e. target. innerText) ; console. log ( this === vm) ; console. log ( this ) ;
} showInfo2 ( number, e ) { console. 1 og ( '你好同学!!' , number) ; console. log ( e. target. innerText) ;
}
</ script>
2,事件修饰符
< body>
< div id = " root" > < h1> 您好,{{name}}</ h1>
< a @click.prevent = " showInfo" href = " https://www.baidu.com/" > 点击提示信息</ a>
< div @click = " showInfo" > < button @click.stop = " showInfo" > 点击提示信息</ button>
</ div>
< button @click.once = " showInfo" > 点击提示信息</ button> </ div>
</ body> < script type = " text/javascript" >
const vm = new vue ( {
el: '#root' ,
data: { name: '张三' ,
} ,
methods: { showInfo ( e ) { alert ( '你好同学!!' ) ; }
}
</ script>
3,键盘事件
1.Vue中常用的按键别名: 回车 =>enter 删除 => delete(捕获“删除”和“退格”键) 退出 =>esc 空格 =>space 换行 =>tab(特殊,必须配合keydown去使用) 上=> up 下=> down 左 =>left 右 =>right2.vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)3.系统修饰键(用法特殊):ctrl、alt、shift、meta (1).配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发。(2).配合keydown使用:正常触发事件。4.也可以使用keycode去指定具体的按键(不推荐)5.Vue.config.keyCodes.自定义键名 =键码,可以去定制按键别名
<! DOCTYPE html)
<html >
< head>
< meta charset = " utf-8" >
< title> 事件的基本使用</ title>
< script src = " ../js/vue.js" > </ script> < body>
< div id = " root" >
< h1> 您好,{{name}}</ h1>
< input type = " text" placeholder = " 按下回车提示输入" @keyup.enter = " showInfo" /> < input type = " text”placeholder=" 按下回车提示输入" @keyup = " showInfo" /> </ div>
< a href = " https://www.baidu.com" @click.prevent.stop = " showInfo" > 点我提示信息</ a>
< input type = " text" placeholder = " 按下回车提示输入" @keyup.ctrl.y = " showInfo" > </ div> </ body>
< script type = " text/javascript" >
Vue. config. keycodes. huiche= 13
const vm = new Vue ( {
el: '#root' ,
data: { name: '张三'
}
methods:{ showInfo ( e ) { console. log ( e. key, e. keycode) console. log ( e. target. value) ; }
}
</ script>
</ html>