前言
接手前同事留下来的项目,发现不少需要继承的 bug(坚强),其中有一个是需要点击按钮,将里面的文字自动填充到输入框里面,跟产品、测试再(斗)三(智)确(斗)认(勇)后,撸起袖子干吧,以下是完成后的效果:

基于vue2和antdUI
1、先准备好两个按钮(可以改成遍历,更方便)
1 2 3
| <a-button type="dashed" class="variable" @click="onCheckVar('{出生年月}')">{出生年月}</a-button > <a-button type="dashed" class="variable" @click="onCheckVar('{姓名}')">{姓名}</a-button>
|
2、准备好几个输入框
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <a-form-item label="测试" v-bind="formItemLayout"> <a-input @focus="onfocusEvent" data-name="test" v-decorator="[ 'test', { rules: [ { required: true, message: '请输入', }, { max: 15, message: '最多允许输入 15 个字符', }, ], }, ]"
/> </a-form-item>
<a-form-item label="出生年月" v-bind="formItemLayout"> <a-textarea @focus="onfocusEvent" data-name="test2" v-decorator="[ 'test2', { rules: [ { required: true, message: '请输入', }, { max: 280, message: '最多允许输入 280 个字符', }, ], }, ]" :rows="8" /> </a-form-item>
<a-form-item label="姓名" v-bind="formItemLayout"> <a-textarea @focus="onfocusEvent" data-name="test3" v-decorator="[ 'test3', { rules: [ { required: true, message: '请输入', }, { max: 40, message: '最多允许输入 40 个字符', }, ], }, ]" :rows="4" /> </a-form-item>
|
3、给每个输入框绑定聚焦事件,并在data定义一个变量保存最后一个输入框的标识
1 2 3 4 5 6 7 8 9
| lastInput:null
onfocusEvent(e) { if (e) { this.lastInput = e.target; this.key = e.target.getAttribute("data-name"); } },
|
4、给每个按钮绑定对应的点击事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| onCheckVar(txt) { this.$nextTick(() => { if (this.lastInput) { this.lastInput.focus(); } else { this.$message.error("请先选择要填充的输入框"); return; } var str = txt; if (typeof document.selection != "undefined") { document.selection.createRange().text = str; } else { this.lastInput.value = this.lastInput.value.substr(0, this.lastInput.selectionStart) + str + this.lastInput.value.substring( this.lastInput.selectionStart, this.lastInput.value.length ); this.form.setFieldsValue({ [this.key]: this.lastInput.value, }); } }); },
|