vue parent-child components pass values to each other

Keywords: Javascript Vue Attribute

Transcendental father

Logic: Click the button of the child component to trigger its click event, trigger the parent-defined event by $emit and pass a value to the parent.

         

 1 <div id="id">
 2 
 3 <h3>Son, how old are you this year? -- {{age}}</h3>
 4 <!-- @getage Custom Events -->
 5 <con1 @getage='getage'></con1>
 6 </div>
 7 <!-- Write a sub-component template -->
 8 <template id="son1">
 9 <!-- Must be wrapped in a large box. -->
10 <div>
11 <h3>I am this year<input type="button" value="Already" @click='click'></h3>
12 </div>
13  
14 </template>
15 
16 <script>
17  //Create a Vue Example
18 var ss = new Vue({
19    el:'#id',
20    data:{
21    // Defining variables age
22     age:' '
23    },
24    methods:{
25   //getage(age) age Values passed in for subclasses     Change the parent after getting it age Value
26 
27       getage(age){
28       this.age = age
29    }
30 },
31  
32    components:{
33      //Define a private sub-template
34        con1:{
35           template:"#son1",
36           data(){
37           return {
38           age:22
39            }
40         },
41           methods:{
42      //  click Click events $emit Triggering parent events and passing values
43            click(){
44               this.$emit('getage',this.age)
45            }
46        }
47     }
48   }
49 
50 })
51 
52 </script>

 

Father's son
 
Logic: The parent passes values to the child only by props:[] passing parent elements to the child.
// Note: Data in all props in a component is passed through the parent component to the child component
// Data in props are read-only and cannot be reassigned
// Get the attribute values of the corresponding attributes on the current component tag
 
 
 <div id="id">
        
        <h2>Your dad, I have.{{money}}</h2>
        <con1 :money='money'></con1>
    </div>
    <script>
    
    var ss = new Vue({
        el:'#id',
        data:{
            money:1000000
        },
        methods:{

        },
        //Define a private subcomponent 
        components:{
            
            con1:{
                template:'<h3>Dad, I know you have{{money}}</h3>',
                //props Parent components pass values to child components
               
                props:['money']

            }
        }
    }) 

    </script>
    

 

 
 
 
 

Posted by patheticsam on Tue, 26 Mar 2019 05:45:28 -0700