Preface
You may have questions at first glance: can v-model and components be linked together? When I was planning to write this article, I thought so too. Let’s sort out this article according to the STAR rules of the resume:
Situation 【Situation】:
When writing a general input component, the child component must be bound to a variable of the parent component dataA, and cannot be passed when the parent component wants to get the value of the component.Over this.$
Take the value and pay it to data,
Instead, the parent component can be directlyYou can get the latest value of the current subcomponent.
Task [Task]:
Implementation: The latest value of the current child component can be obtained directly in the parent component.
Action:
First of all, we need to understand the v-model command. Many students who have carefully read the complete vue document may already know about v-model.
What v-model officially said is: This is actually a short form, and v-model actually executes the following binding:
<input type="text" v-bind:value="dataA" v-on:input="dataA = $" />
v-model is a process in which the value is dynamically bound to value, and then listens to input's inpit event to get the value and assign it to dataA.
Let’s talk about the value attribute of input. A value props attribute should be defined inside the component so that the value passed by the parent component can be dynamically bound;
Another thing to do inside the component:
Dynamically calculate (get and set) the value of currentValue, using the get and set functions of the vue object;
By this point, we can solve the above problems;
First define a general input component:
('my-component',{ template:'<div><input type="text" type="text" v-model="currentValue"/></div>', data:function(){ return { // Bidirectional binding value - Must currentValue: } }, props:['value'],// Set value to props property - Must computed:{ currentValue: { // Dynamically calculate the value of currentValue get:function() { return ; }, set:function(val) { this.$emit('input', val); } } } })
Bind to a field in the vue instance in HTML;
<div > <my-component v-for="(val,key) in postData" v-model="postData[key]"></my-component> <button @click="showValue">Print object value</button> </div>
Write a method in the example
Print the value we bound;
var demo_01 = new Vue({ el:'#demo_01', data:{ postData:{ name:'Li Lei', age:'80', describ:'This is a legendary character' } }, methods:{ showValue:function(){ () } } });
Will there be no need to be tedious and tedious in the futurethis.$
How to get the value?
Results [Result]:
Provides an effective solution to the input class component value scheme and has been deployed to implement it.
Summarize
The above is all about vue2.0 components and v-model. I hope that the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your help.