“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
In the last article we looked at parent-child communication, portal: Understanding the basic use of parent-child communication for Vue component communication
Today we are going to talk about parent-child communication, which means that a child component communicates with a parent component through events.
You can use this.$emit(‘show’,{}) not only to emit events but also to pass data.
The following code:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="app">
<father></father>
</div>
<script src="vue.js"></script>
<script type="text/javascript">
Vue.component('father', {template:Child @ show ` < div > < = "showfn" > < / child > < div v - if = "show" > grade: 88 < / div > < / div > `.data:function(){
return {
show:false}},methods: {showfn:function(data){
this.show = true;
console.log(data);// Data is the data that is passed when an event is emitted with $emit.}}}); Vue.component('child', {template:'< button@click ="onClick"> here is the sub-component '.methods: {onClick:function(){
this.$emit('show', {a:1.b:2.c:3});// Trigger the event}}});new Vue({
el:'#app'
});
</script>
</body>
</html>
Copy the code
The basic steps are shown in the code above
- Vue.com Ponent defines two components, father and child. The reason is to declare configuration items required by the component, such as template, methods, data, and so on
- We can see that the parent component contains the child component, that is, the parent component’s template contains the child component;
- Emit related events in the child component and use $emit(‘ event name ‘,{data to be passed}) in the event method to emit other events. This makes the event listen in the child component of the parent component and then call the corresponding method in the parent component that triggered the event.
In this way, the communication between children and parents is realized. In a nutshell, a child component triggers related events that are passed to the parent component, and the parent component performs related operations.
Finally, there are many ways of communication, whether it is father-child communication or father-child communication, there are different ways to implement it. I just talk about one of them here. You can read the official documents for more details about other ways
That is all the content of this article, welcome to like, comment and bookmark, like to remember to follow oh ~