先上圖
要實現一個相似於這樣的輸入框,並且有幾個頁面都須要相似的輸入框(輸入身份證後四位/輸入支付密碼),就準備擼一個小組件。javascript
# 原理
在一個輸入框中輸入一串字符串,而後根據下標index分別填入框裏,爲了代碼的可讀性,我這裏框就用ul,li來寫
## 子組件
```javascript
<template>
<div>
<label for="code">
<ul class="code-box">
<li class="code-number" v-for="(item, index) in length" :key="index">
{{ code[index] }}
</li>
</ul>
</label>
<input
class="code-input"
v-model="code"
:maxlength="length"
type="number"
id="code"
@keyup.13="next()"
/>
</div>
</template>html
<script>
export default {
name: "CodeInput",
props: {
length: {
type: Number,
default: 6
}
},
data() {
return {
code: ""
};
},
methods: {
getCode() {
return this.code;
},
next() {
this.$emit("func", this.code);
}
}
};
</script>
<style scoped>
.code-box {
border-radius: 8px;
border: 1px solid #cccccc;
display: inline-flex;
}
.code-number {
width: 56px;
height: 58px;
border-right: solid #cccccc 1px;
text-align: center;
font-size: 30px;
color: red;
}
.code-number:last-child {
border-right: 0;
}
.code-input {
height: 0.44rem;
position: fixed;
outline: none;
color: transparent;
text-shadow: 0 0 0 transparent;
width: 300%;
margin-left: 100%;
}
button {
width: 100px;
height: 60px;
}
</style>java
```
## 父組件less
```javascript
<template>
<div>
<security-code v-model="code" v-on:func="show"></security-code>
</div>
</template>
<script>
import securityCode from "../components/password";
export default {
components: { securityCode },
data() {
return {
code: ""
};
},
methods: {
show() {
console.log(this.code);
this.$router.push({ path: "/" });
}
}
};
</script>
<style lang="less" scoped></style>flex
```this
# 注意點
label屬性:html的label屬性能夠根據input的id擴大input的點擊面積。spa
@keyup.13="next()":這一句是指手機鍵盤的回車/肯定/前進鍵觸發 的事件3d
子組件input的位置:我是經過絕對定位使他不在我可視位置上,不能讓他display:nonecode
附加:由於通常父子組件的style都是設置了scoped,若是想對設置了scoped的子組件裏的元素進行控制能夠使用 ’>>>’ 或者 ’deep’,這個本身百度不少方法component