vue.js 事件绑定

1.添加事件监听 v-on

(1)使用v-on指令可以添加事件监听,语法:
v-on:eventName="fn" 也可以简写成 @:eventName="fn"
(2)参数:$event就是当前触发事件的元素,即使不传$event,在回调函数中也可以使用event这个参数

基本使用:

<div id="app">
    <button v-on:click="test">点我</button>
    <button v-on:click="test2('hello vue')">点我2</button>
    <button v-on:click="test3($event)">点我3</button>
    <button v-on:click="test4">点我4</button>
</div>
methods: {
    test() {
        console.log('hi');
    },
    test2(content) {
        console.log(content);
    },
    test3(event) {
        console.log(event.target);
    },
    test4(){
       //即使不传$event,在回调函数中也可以使用event这个参数
       console.log(event.target.innerText);
    }
}

其他事件:

<body>
    <div id="app">
        <!-- 点击事件 -->
        <button @click="testClick">点我</button>
        <!-- input事件 -->
        <input type="text" @input="testInput">
        <!-- change事件 -->
        <select @change="testChange">
            <option value="020">广州</option>
            <option value="021">上海</option>
        </select>
    </div>
</body>
<script>
    new Vue({
        el:"#app",
        data:{},
        methods:{
            testClick(){
                console.log('Click')
            },
            testInput(){
                console.log('Input')
            },
            testChange(){
                console.log('Change')
            }
        }
    })
</script>

2.事件修饰符

事件修饰符用来控制事件的冒泡和默认行为,共有2个:
.stop:阻止事件冒泡
.prevent:阻止默认事件

基本使用:

<!-- 阻止事件冒泡 -->
<div id="big" @click="test">
    <div id="small" @click.stop="test2"></div>
</div>
<!-- 阻止默认事件,点击a链接不会发生跳转,只会执行test方法的代码 -->
<a href="https://www.baidu.com/" @click.prevent="test">百度一下</a>

3.按键修饰符

按键修饰符用来监听某个按键是否被按下

使用@keyup指令可以为元素添加键盘事件,例如:

<!-- 任何按键按下都会触发回调函数 -->
<textarea @keyup="testKeyup" cols="30" rows="10"></textarea>

如果我们想在特定按键按下才触发回调的话就添加按键修饰符或按键码,例如:
语法: @keyup.按键修饰符=回调函数
语法: @keyup.按键码=回调函数

<!-- 只有回车键按下的时候才会触发回调函数 -->
<!-- 下面的两种写法效果是一致的 -->

<!--使用按键码,回车键的keyCode是13 -->
<textarea @keyup.13="testKeyup" cols="30" rows="10"></textarea>
<!--使用按键修饰符,因为回车键比较常用,所以vue为他设置了名称,可以直接使用enter来代替。 -->
<textarea @keyup.enter="testKeyup" cols="30" rows="10"></textarea>
methods: {
    testKeyup() {
        console.log('回车键被按下了');
    }
}

Vue 提供了绝大多数常用的键修饰符:

  • .enter
  • .tab
  • .delete (捕获“删除”和“退格”键)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

其余按键可以用按键码

<!--q的keyCode是81,当按下q键时会触发test方法 -->
<input type="text" value="hello" @keyup.81="test">

你可以通过全局 Vue.config.keyCodes.自定义按键修饰=按键码,来自定义按键修饰符,例如:

//q的keyCode是81
<input type="text" value="hello" @keyup.q="test">

Vue.config.keyCodes.q=81

猜你喜欢

转载自www.cnblogs.com/OrochiZ-/p/11824489.html