vue《四》( 键盘事件,样式绑定)

本文介绍Vue.js中处理键盘事件的方法及样式绑定的应用,包括keydown、keyup事件的使用和动态样式的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,键盘事件

1.keydown()键盘键入,触发事件

效果图:

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript">
        window.onload = function(){
            var vm = new Vue({
                el:'#test',
                methods:{
                    show:function(){
                        alert("键盘键入");
                        //event.cancelBubble = true;
                    },
                }
            });
        }
    </script>
</head>
<body>
<div id="test">
    <input type="text" placeholder="请输入" @keydown="show()">
</div>
</body>
</html>

2.点击回车键触发事件

<div id="test">
        <input type="text" placeholder="请输入" @keyup.13="show($event)"> 
    </div>

3.其它事件

@keyup.13 回车
@keyup.enter 回车
@keyup.left 左键
@keyup.right 右键
@keyup.up 上键
@keyup.down 下键
@keyup.delete 删除键
......

二,样式绑定

样式:


具体代码:

<div id="test2">
    <img src="{{url}}">
    <img v-bind:src="url">
</div>
var vm2 = new Vue({
                el:'#test2',
                data:{
                    url:'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png',
                },
            });

src="{{url}}"这种方式不能显示 图片

在Vue中,HTML属性有特有的写法  v-bind:src="url"可以简写成:src="url"

宽度和高端等HTML属性可以直接使用,建议按照vue中写法写代码。

<img :src="url" width="w" height="h" :title="t">
var vm2 = new Vue({
                el:'#test2',
                data:{
                    url:'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png',
                    w:'110px',
                    h:'110px',
                    t:'图片标题'
                },
            });

class和style

数组用法:v-bind:class="[red,b]" 
绑定的样式数据:red,b

<div id="test3">
    <span v-bind:class="[red,b]">这里是样式</span>
</div>
   <script type="text/javascript">
        window.onload = function(){
           
            var vm3 = new Vue({
                el:'#test3',
                data:{
                    red:'red', //值red是定义的样式名
                    b:'b',
                },
            });
        }
    </script>
    <style type="text/css">
        .red{color: red}
        .b{background: blue}
    </style>

传入一个对象,以动态的切换class。

<div id="test4">
    <span v-bind:class="{red:true}">文字</span> <!-- 样式生效 -->
    <span v-bind:class="{red:false}">文字</span> <!-- 样式不生效 -->
    <span v-bind:class="{red}">文字</span><!-- 默认是true -->
</div>

style

样式:


代码:

<div id="test5">
    <p :style="{color:green}">第五个测试</p>
</div>
var vm5 = new Vue({
                el:'#test5',
                data:{
                    green:'green',
                },
            });

样式:


代码:

<div id="test6">
    <strong :style="[a,b]">第六个测试</strong>
</div>
var vm6 = new Vue({
                el:'#test6',
                data:{
                    a:{color:'red'},
                    b:{background:'green'}
                },
            });


### Vue3 中实现键盘事件监听 在 Vue3 中,可以通过多种方式实现在组件内监听键盘事件的功能。下面展示两种常见的方式。 #### 使用 `@keyup` 或者 `@keydown` 模板指令绑定事件处理器 通过模板内的 v-on 指令可以方便地为 DOM 绑定事件监听器。这里给出一个简单的例子,当按下特定时更改页面上的计数器数值: ```html <script setup> import { ref, onMounted, beforeUnmount } from 'vue' const keyCounter = ref({ ArrowUp: 0, ArrowDown: 0 }) function handleKeydown(event) { switch (event.key) { case "ArrowUp": keyCounter.value.ArrowUp += 1; break; case "ArrowDown": keyCounter.value.ArrowDown += 1; break; } } // 添加全局事件监听器 onMounted(() => window.addEventListener('keydown', handleKeydown)) // 移除全局事件监听器以防内存泄漏 beforeUnmount(() => window.removeEventListener('keydown', handleKeydown)) </script> <template> <button @click="keyCounter.ArrowUp++">Simulate Up Key Press</button> <button @click="keyCounter.ArrowDown++">Simulate Down Key Press</button> <p>Up arrow pressed {{ keyCounter.ArrowUp }} time(s).</p> <p>Down arrow pressed {{ keyCounter.ArrowDown }} time(s).</p> </template> ``` 此代码片段展示了如何利用 `ref()` 创建响应式的数据属性,并且使用 `onMounted` 和 `beforeUnmount` 生命周期钩子来管理事件监听器的添加与移除[^1]。 #### 结合计算属性和样式动态调整界面状态 另一个更复杂的案例涉及到了根据不同的按改变整个网页背景的颜色。这通常涉及到定义一组预设好的颜色映射表以及相应的处理逻辑。如下所示: ```html <script setup> import { ref, reactive, computed, onMounted, beforeUnmount } from 'vue'; let currentColor = ref('#ffffff'); const colorKeys = reactive({ a: '#ffcccc', s: '#ccffff', d: '#d9bfff' }); function changeBackgroundColor(event){ let newColor = colorKeys[event.key]; if(newColor !== undefined){ currentColor.value = newColor; } } onMounted(() => document.body.style.backgroundColor = currentColor.value); onMounted(() => addEventListener('keydown', changeBackgroundColor)); beforeUnmount(() => removeEventListener('keydown', changeBackgroundColor)); </script> <style scoped> body{ transition: background-color .5s ease-in-out; } </style> <template> <div :style="{ backgroundColor: currentColor}"> <h2 style="text-align:center;">Press A/S/D to Change Background Color!</h2> </div> </template> ``` 上述示例不仅实现了基于按输入修改页面样式的功能,还加入了 CSS 过渡效果使得视觉变化更加平滑自然[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值