vue Value transfer between components is divided into value transfer from parent component to child component and value transfer from child component to parent component

One, Pass value from parent component to child component

Introduce child component in parent component,
Parent componentjs Property value to be passed, The following is a dynamic transfer,name You can define methods, Dynamic modification in method, If dynamic transmission is not required, Then directly use the attribute to define the value

parent.vue


<template> <child v-bind:name="name"></child> </template> <script> import
child from "./child.vue" export default { components: {child}, data(){ return
{name:" Zhang San"} } } </script>


Subcomponent definitionprops Receive the value passed by the parent component, as follows:

child.vue



<template> <div>{{name}}</div> </template> <script> export default {
props:["name"] } </script> Two, Pass value from child component to parent component


First, introduce the child component into the parent component, Define a method to receive values passed by subcomponents, If you only need to know that a subcomponent completes an operation, Can not transfer value, Define methods only, as follows( Pass value from child component to parent component):

parent.vue


<template> <child @childToParent="child"></child> </template> <script> import
child from "./child.vue" export default { components: {child}, methods:{
child(data){ console.log(data); } } } </script> Define a method in a subcomponent, Pass value to parent component, as follows:


child.vue


<template> <button @click="childClick"> click</button> </template> <script> export
default { methods:{ childClick(){ this.$emit("childToParent","I am child."); }
} } </script>
Three, Parent component calls child component method

First define the method in the subcomponent, After the child component is introduced into the parent component, When using subcomponents, Bind oneref, This enables the parent component to call the child component's methods

parent.vue


<template> <child ref="child"></child> <button @click="click">click</button>
</template> <script> import child from "./child.vue" export default {
components: {child}, methods:{ click(){ this.$refs.child.init(); } } } </script>

child.vue


<template> <p>{{name}}</p> </template> <script> export default { data(){
return { name:'' } } methods:{ init(){ this.name="jack"; } } } </script>