修改Uniapp input 组件不刷新视图问题
uni-app 的input是原生组件外部修改 value 不会刷新视图改 key 强制销毁重建组件u-inputtemplate view classinput-wrapper !-- 用 key 强制重新渲染解决 uni-app input 值不同步的问题 -- input classuni-input :keyinputKey :placeholderplaceholder :valuevalue :typeinputType :passwordshowPassword inputhandleInput v-bind$attrs / uni-icons v-ifshowClearIcon typeclose classuni-icon :sizeiconSize :coloriconColor clickhandleClearValue / uni-icons v-ifisPassWord classuni-icon :sizeiconSize :coloriconColor clickchangePassword :typeshowPassword ? eye-filled : eye-slash-filled / /view /template script export default { name: u-input, inheritAttrs: false, props: { value: { type: [String, Number], default: , }, type: { type: String, default: text, }, placeholder: { type: String, default: 请输入, }, iconSize:{ type:Number, default:20 }, iconColor:{ type:String, default:#808080 } }, data() { return { showPassword: false, showClearIcon: false, inputKey: 0, // 用于强制刷新 input }; }, computed: { isPassWord() { return this.type password || this.type safe-password; }, inputType(){ this.showPassword this.isPassWord return this.isPassWord?:this.type } }, watch: { // 监听 value 变化保持清除按钮状态同步 value: { immediate: true, handler(val) { this.showClearIcon val val.length 0; }, }, }, methods: { handleInput(event) { const val event.detail.value; this.$emit(input, val); this.showClearIcon val.length 0; }, handleClearValue() { this.$emit(input, ); this.showClearIcon false; this.inputKey; }, changePassword() { this.showPassword !this.showPassword; }, }, }; /script style scoped langscss .input-wrapper { display: flex; flex-direction: row; align-items: center; width: 100%; } .uni-input { flex: 1; width: 100%; } .uni-icon{ margin: 0 $uni-spacing-row-sm; } /styleinheritAttrs: false阻止$attrs自动绑定到组件根元素view上v-bind$attrs绑定到input未在 props 中声明的属性全部透传给原生 input使用组件!-- placeholder、maxlength、disabled 等全部透传 -- u-input v-modelform.username placeholder请输入用户名 maxlength20 :disabledisDisabled confirm-typedone / u-input v-modelform.password typepassword placeholder请输入密码 maxlength32 /