使用vue实现简单键盘的示例(支持移动端和pc端)(2)
KeyInput.vue
<template>
<div>
<input type="text" ref="keyboard" v-model="inputValue" @focus="onFocus">
<Keyboard :option="option" @keyVal="getInputValue" @close="option.show = false"></Keyboard>
</div>
</template>
<script>
import Keyboard from '../components/Keyboard'
export default {
components: {
Keyboard
},
data() {
return {
option: {
show: false,
sourceDom: ''
},
inputValue: ''
}
},
props: {},
created() {},
methods: {
getInputValue(val) {
if(val === 'delete'){
this.inputValue = this.inputValue.slice(0,this.inputValue.length -1)
}else{
this.inputValue += val
}
},
onFocus() {
this.$set(this.option, 'show', true)
this.$set(this.option, 'sourceDom', this.$refs['keyboard'])
},
//获取光标位置
getCursorPosition() {
let doc = this.$refs['keyboard']
if (doc.selectionStart) return doc.selectionStart
return -1
},
//设置光标位置 暂未实现
setCursorPosition(pos) {
let doc = this.$refs['keyboard']
console.log(doc.setSelectionRange)
doc.focus()
doc.setSelectionRange(1,3)
}
}
}
</script>
<style lang="less" scoped>
</style>
使用demo
<template>
<div>
<key-input class="demo-class"></key-input>
</div>
</template>
<script>
import KeyInput from '../components/KeyInput'
export default {
components: {
KeyInput
},
data() {
return {
}
},
created() {},
methods: {
}
}
</script>
<style lang="less">
body{
background: #efefef;
}
.demo-class{
input{
border:1px solid #ccc;
outline: none;
height: 30px;
font-size: 16px;
letter-spacing: 2px;
padding: 0 5px;
}
}
</style>
完整代码:https://github.com/dawnyu/vue-keyborad
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
