实现一:vue中的v-model + vue-input-autowidth插件
1.npm i vue-input-autowidth。
2.在main.js中import, 并使用Vue.use()。
3.封装组件,带有label的input组件;使用<AutoWidthInput :label="名称", v-model="value" />
<template> <div class="autoInputContainer"> <label class="inputLable">{{label}}</label> <div style="display: inline-block" @mouseenter="enter" @mouseleave="leave"> <input type="text" v-autowidth="{maxWidth: '500px', minWidth: '78px', comfortZone: 0}" placeholder="请输入" class="autoInput" @input="update" :value="value" @blur="inputBlur" @focus="inputFocus" ref="input" /> <i class="el-icon-circle-close close" @click="clearValue" v-show="closeDisable"></i> </div> </div> </template> <script> export default { name: 'AutoWidthInput', model: { prop: 'value', event: 'input' }, props:{ value:{ type:[ Number , String], default:'' }, label:{ type:[ String], default:'' } }, data() { return { closeDisable: false, isFocus:false // input框是否聚焦 }; }, methods: { update(e){ this.$emit('input',e.target.value) if(e.target.value!==''){ this.closeDisable = true // 显示清空按钮 } }, clearValue(){ this.$emit('input','') this.$refs.input.focus() }, inputBlur(){ }, inputFocus(e){ this.isFocus = true if(e.target.value!==''){ this.closeDisable = true } }, // hover效果 enter (e){ if(this.value!==''){ this.closeDisable = true } }, leave (e){ this.closeDisable = false } } }; </script> <style lang="scss" scoped> .autoInputContainer{ position: relative; padding: 5px 0; float: left; margin-right: 15px; label{ font-size: 13px; display: inline-block; padding-right: 15px;; } .autoInput{ box-sizing: border-box; color: #606266; display: inline-block; font-size: inherit; height: 32px; line-height: 12px; background-color: #FFF; background-image: none; border-radius: 4px; border: 1px solid #DCDFE6; white-space: nowrap; font-size: 12px; padding: 0 10px; padding-right: 20px; } .autoInput:hover{ border-color: #C0C4CC } .close{ position: absolute; top: 50%; transform: translateY(-50%); right: 5px; font-size: 14px; cursor: pointer; color: #DCDFE6; } .close:hover{ color: #979b9f; } } </style>
实现二:利用html5中的contenteditable
<div contenteditable="true" class="inputWidth" @input="change" ref="input1">{{input}}</div> </div> </template> <script setup> import {ref} from 'vue' const input = ref('') const input1 = ref(null) console.log('input1:',input1) const change = ()=> { input.value = input1.value.innerHTML console.log(input.value) } </script> <style scoped> .inputWidth{ display: inline-block; min- 100px; max- 500px; border: 1px solid #ccc; padding: 10px; white-space: nowrap; } </style>