vue parent-child component pass value

parent-child component pass value

Passing values ​​from parent component to child component

Mainly through props

// 1. Create a child component
<template>
    < div > child component </ div > 
</ template >

// 2. Create a parent component 
< template > 
    < div > parent component </ div > 
</ template > 
< script > export default {

        data(){
            return {
                 msg : 'I want to pass the data to the child component' ,
            }
        }
    }
</script>

// 3. Bind the msg parameter in the parent component with v-bind and pass it to the child component (son is a custom attribute) 
//parent component 
   < child  :son = "msg" > child component </ child >

//Subcomponent 
props:[ "son" ], //Use props to receive the parameters from the parent component

console .log( this .son) //Get msg in parent component

Note: The parameters received by props are read-only and cannot be modified.

child component pass value to parent component

Mainly through this.$emit(‘function’, parameters to be passed)

//Child component 
this .$emit( ​​'getchildp' , 1 )

//Parent component 
<child @getchildp= "getmsg" > </ child >

getmsg(e){
    console.log(e) //1 
}

Leave a Comment

Your email address will not be published. Required fields are marked *