Parent-son component communication
The parent component displays the input box for adding new data, and the child component displays the array information.
Scene 1: Pass a whole array directly
Parent component is used in child component tagsv-bind
Bind an attribute namelist
, the attribute value is the array to be passedlist
Subcomponent calls functionsdefineProps
, receive data transmitted from the parent component.defineProps
The function is introduced by vue by default. It accepts an object as a parameter by default. The object contains a field, and the field name is the property name bound by the parent component.list
, the field value is another object, the object contains the data type that the child component expects to receivetype
and default valuesdefault
, here expects to receive an array, with the default value being an empty array.list
You can directly use it in the template module
Parent component code:
<template> <div class="inputGroup"> <input type="text" v-model="value"> <button @click="add">Add to</button> </div> <Child :list="list"> </Child> // The parent component passes the value v-bind binding to the child component</template> <script setup> import Child from '@/components/' // Introduce subcomponents import { ref } from 'vue' const value = ref('') const list = ref(['html', 'css', 'js']) const add = () => { () = '' } </script>
Subcomponent code:
<template> <div class="child"> <ul> <li v-for="item in list">{{ item }}</li> </ul> </div> </template> <script setup> defineProps({ // Subcomponents receive using defineProps list: { type: Array, required: true, default: () => [] } }) </script>
This communication process itself is a responsive process, so after the parent component passes the past property value list to the child component, the child component will receive the latest value again. Since the list is defined as responsive, the browser will eventually render the newly added value successfully.
Scenario 2: Only the newly added value is passed
Parent component is used in child component tagsv-bind
Bind an attribute namemsg
, the attribute value is the new data to be passedtoChild
Subcomponent defines a variableprops
take overdefineProps
The result of function execution, and then the received new dataAdded to the subcomponent already defined
list
In the array
Parent component code:
<template> <div class="inputGroup"> <input type="text" v-model="value"> <button @click="add">Add to</button> </div> <Child :msg="toChild"> </Child> </template> <script setup> import Child from '@/components/' // Introduce subcomponents import { ref } from 'vue' const value = ref('') const toChild = ref('') const add = () => { = } </script>
Subcomponent code:
<template> <div class="child"> <ul> <li v-for="item in list">{{ item }}</li> </ul> </div> </template> <script setup> import { ref, watch } from 'vue' const list = ref(['html', 'css', 'js']) const props = defineProps({ msg: '' // Direct abbreviation, no longer write the value corresponding to msg into an object }) watch( // The value of the monitored change, and once the change is changed, the callback function is executed () => , (newVal, oldVal) => { (newVal) } ) </script>
defineProps
The fields in the function can be used directly in the template, but if you want to use them in a js script, you need a variable to receive the execution result of this function.
Notice: Not directly here
()
, but needwatch
rightThe value of the listener is because: the list needs to be updated
()
This js code is executed repeatedly, and the js code will not be executed the second time after the browser renders the first page of the browser. Therefore, the watch function needs to actively execute the update of the list after monitoring the value changes.
Children and parent component communication one
The parent component displays array information, and the child component displays input box to add new data
With the publish subscription mechanism, subcomponent callsdefineEmits
The function accepts an array as a parameter, array[ 'new' ]
Indicates that the component can trigger a name called'new'
custom event, return toemits
Object, you can use it to triggernew
event. After clicking the button, callemits
The function publishes events, and the parameters passed are the event names to be transmitted to the parent component.new
and event value
The parent component subscribes to the event and obtains the value provided by the child component through the event parameter.
Parent component code:
<template> <!-- subscriptionnewevent--> <Child @new="handle"></Child> <div class="child"> <ul> <li v-for="item in list">{{ item }}</li> </ul> </div> </template> <script setup> import Child from '@/components/' import { ref } from 'vue' const list = ref(['html', 'css', 'js']) const handle = (event) => { // The event event parameter is actually the value transmitted when the child component publishes the event (event) } </script>
Subcomponent code:
<template> <div class="inputGroup"> <input type="text" v-model="value"> <button @click="add">Add to</button> </div> </template> <script setup> import { ref } from 'vue' const value = ref('') const emits = defineEmits(['new']) // Create a new event const add = () => { emits('new', ) // Publish an event } </script>
Children and Parent Component Communication II
The parent component displays array information, and the child component displays input box is used to add new data
Can be used but not recommended
Iflist
The array is made into a basket, and the new data is added to make an apple. Then the son and father component communication is one that the son throws the apple to the father, and the father then puts the apple into the basket; the son and father component communication is two that the father shares the basket with the son, and the son puts the apple into the basket.
The parent component is definedlist
Array, byv-model:list
Directive to parent componentlist
Properties and subcomponentslist
prop is bidirectional, meaning that when list is modified inside child components, these changes are also reflected back to the list property of the parent component
The way child components receive list is to usedefineProps
take over
Parent component code:
<template> <Child v-model:list="list"></Child> <div class="child"> <ul> <li v-for="item in list">{{ item }}</li> </ul> </div> </template> <script setup> import Child from '@/components/' import { ref } from 'vue' const list = ref(['html', 'css', 'js']) </script>
Subcomponent code:
<template> <div class="inputGroup"> <input type="text" v-model="value"> <button @click="add">Add to</button> </div> </template> <script setup> import { ref, defineProps } from 'vue' const value = ref('') const props = defineProps({ list: { type: Array, default: () => [] } }) const add = () => { () } </script>
However, the vue official does not recommend that we let the child components directly operate the data given by the parent component, because this will cause the data flow to be very confusing. Normally, if my own array is to be modified, I should change it myself, rather than handing it over to others to modify it.
Optimized version
Therefore, the js code of the subcomponent should be optimized to the following
usedefineEmits
Functions to declare events that components can triggerupdate:list
, in Vue,update:
Events that begin are usually used to notify parent component of changes in data internal to child components.arr
take overlist
Reference to prop, and then update thearr
Throw it out,v-model:list
It will automatically get the latest value
<script setup> import { ref, defineProps } from 'vue' const value = ref('') const props = defineProps({ list: { type: Array, default: () => [] } }) const emits = defineEmits(['update:list']) const add = () => { const arr = () emits('update:list', arr) } </script>
Children and Parent Component Communication Three
The parent component displays array information, and the child component displays input box is used to add new data
The parent component reads directly to the updated child componentlist
: A responsive variable is defined in the parent componentchildRef
,childRef
As a tag, you can get any data of the child component through childRef
The child component completes the update of the list by itself and calls itdefineExpose
Function, specifylist
The data can be accessed externally
Parent component code:
<template> <Child ref="childRef"></Child> <div class="child"> <ul> <li v-for="item in childRef?.list">{{ item }}</li> </ul> </div> </template> <script setup> import Child from '@/components/' import { ref, onMounted } from 'vue' const childRef = ref(null) </script>
Subcomponent code:
<template> <div class="inputGroup"> <input type="text" v-model="value"> <button @click="add">Add to</button> </div> </template> <script setup> import { ref, defineProps } from 'vue' const value = ref('') const list = ref(['html', 'css', 'js']) const add = () => { () } defineExpose({ list }) // Voluntary exposure of data</script>
ref
is a special property in Vue that allows us to refer to child components or DOM elements in parent components
item in childRef?.list
middle,?
It is the new syntax of ES6. When childrenRef has a value, the following .list will not be read when it is not available. (This arrangement is because when the parent component executes this line of code, the child component may not be loaded yet, so as not to report an error)
Summarize
-
Parent-son component communication: The parent component will value
v-bind
Bind to subcomponents, and subcomponents usedefineProps
take over - Children's components communicate with parent components: With the help ofPublish SubscribeMechanism, the child component is responsible for publishing events and carrying parameters. The parent component subscribes to the event and obtains the value provided by the child component through the event parameters.
-
Children's components communicate with parent components: Parent component with help
v-model
Bind data to subcomponents, and subcomponents are created'update:xxxx'
Event and modify the received dataemits
come out -
Children's components communicate with parent components: Parent component passes
ref
Get subcomponentsdefineExpose()
Exposed data
The above is the detailed content of all the methods of vue parent-child component communication. For more information about vue parent-child component communication, please follow my other related articles!