用VUE实现一个数字小键盘组件,实现按#号发送事件,及以显示键盘位置做个参数可根据鼠标点击显示
简单的东西直接上图上代码:
<script setup>
import { ref, watch, onMounted ,defineEmits} from 'vue';
// 定义响应式数据
const inputDisplay = ref('');
// 定义按键数组
const keys = ref(
[
'1', '2', '3','A',
'4', '5', '6', 'B',
'7', '8', '9','C',
'0', '*', '#','D'
]);
const props = defineProps({
position: {
type: Array,
default: [0,0]
}
});
const onDeleteKey=()=>{
if(inputDisplay.value){
inputDisplay.value = inputDisplay.value.slice(0, -1);
}
}
const $emit = defineEmits(['sendCommand', 'update:inputDisplay']);
// 定义按键按下时的事件处理函数
const onKeyPress = (key) => {
if (key === '#') {
// 发送命令
$emit('sendCommand', inputDisplay.value);
inputDisplay.value = ''; // 清空输入
} else {
inputDisplay.value += key;
}
};
// 监听inputDisplay的变化,以便外部可以获取到最新的值
watch(inputDisplay, (newValue) => {
$emit('update:inputDisplay', newValue);
});
onMounted(() => {
// 组件挂载后的逻辑
});
</script>
<template>
<div class="sip-data-keyboard" :style="{left:position[0]+'px',top:position[1]+'px'}">
<div class="keys">
<!-- 使用v-for循环渲染按键 -->
<div
v-for="key in keys"
:key="key"
class="key"
@click="onKeyPress(key)"
>
{{ key }}
</div>
</div>
<div class="input-display">
<input type="text" class="input-result" v-model="inputDisplay" />
<div class="delete-key iconfont icon-digital-keyboard-delete" @click="onDeleteKey"></div>
</div>
</div>
</template>
<style lang="scss" scoped>
.sip-data-keyboard {
/* 键盘容器样式 */
position: absolute;
left:0;top:0;
background: #5a5a5a;
padding:15px;
border-radius: 5px;
}
.keys {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.key {
width: 50px;
height: 50px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.key:hover {
background: #ccc;
}
.input-display {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
display: flex;
}
.input-display .input-result {
height: 30px;
border: none;
outline: none;
background: transparent;
color: #fff;
font-size: 14px;
font-weight: bold;
line-height: 30px;
text-align: left;
flex: 1;
}
.input-display .delete-key {
cursor: pointer;
font-size:30px;
line-height:30px;
margin:0;padding:0;
&:hover {
color: #ccc;
}
}
</style>