Source of the problem
When writing input components, you need to have a clear button, but if you directly modify the parent's pass value in the prop, an error will be reported. However, if the parent cannot be updated without modifying it, it will also bring development problems.
solve
v-model completes bidirectional binding of most data
<input type="text" :value="inputValue" @change="$emit('change',$)" @blur="$emit('blur',$)" @focus="$emit('focus',$)" @input ="$emit('input',$)" >
Four events pass the input event, used at the parent level
<g-input v-model="num"></g-input>
However, there are difficulties in clearing operations, because no matter how you operate, the data driver on vue cannot be triggered. The data maintained on simple clearing of the child components is not synchronized to the parent. The best solution here is undoubtedly a one-way data flow, allowing the child component to notify the parent when an event occurs, and the parent element passes the value changes, and then change the child component. But I feel that doing this will go against the original intention of using v-model, but there is nothing I can do about it
Dom binding event to be listened to
In the subcomponent:
<div @click="clear"> <g-icon></g-icon> </div>
Tell the parent to clear the data
clear(){ this.$emit('inputclear',{clear:''}) }
The above two can be combined into
<div @click="$emit('inputclear',{clear:''})"> <g-icon v-if="isClearShow" icon="error" class="clearForInput" ></g-icon> </div>
In parent:
<g-input v-model="num" @inputclear="num = $"></g-input>
It's OK now
Summarize
The above is the v-model clearing operation of input in vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!