Summary of VueJs parent-child component communication methods
This time I will bring you a summary of the communication methods of VueJs parent-child components. What are the precautions for VueJs parent-child component communication? The following is a practical case, let's take a look.
Component (Father-Child Communication)
1. Summary
Define another component within a component, which is called Parent-child components.
But it should be noted that: 1. Child components can only be used inside the parent component (written in the parent component template); The data on, the scope of each component instance is independent;
How to complete the communication between father and son, in a simple sentence: props down, events up: the parent component passes data downward to the child component through props , the child component sends to the parent component through events
Pass from parent to child: Props
Pass from child to parent: Child: $emit(eventName) Parent $on(eventName) Parent accesses child: ref
Let’s explain the three cases below:
2. Pass from father to son: Props The scope of the component instance is isolated. This means that you cannot (and should not) reference the parent component's data directly within the child component's template. To allow the child component to use the data of the parent component, you need to use the props option of the child component
Using Prop to transfer data includes static and dynamic forms. Let’s first introduce static props
1, static props
<script src="https://unpkg.com/vue"></script> <p id="example"> <parent></parent> </p> <script> //要想子组件能够获取父组件的,那么在子组件必须申明:props var childNode = { template: '<p>{{message}}</p>', props: ['message'] } //这里的message要和上面props中值一致 var parentNode = { template: ` <p class="parent"> <child message="我是"></child> <child message="徐小小"></child> </p>`, components: { 'child': childNode } }; // 创建根实例 new Vue({ el: '#example', components: { 'parent': parentNode } }) </script>
Effect:
## Naming convention:
<script> //这里需要注意的是props可以写成['my-message']或者['myMessage']都是可以的 //但是template里的属性名,只能是驼峰式{{myMessage}},如果也写成{{my-message}}那么是无效的 var childNode = { template: '<p>{{myMessage}}</p>', props: ['myMessage'] } //这里的属性名为my-message var parentNode = { template: ` <p class="parent"> <child my-message="我是"></child> <child my-message="徐小小"></child> </p>`, components: { 'child': childNode } }; </script>
2. Dynamic props
var childNode = { template: '<p>{{myMessage}}</p>', props: ['my-message'] } var parentNode = { template: ` <p class="parent"> <child :my-message="data1"></child> <child :my-message="data2"></child> </p>`, components: { 'child': childNode }, data() { return { 'data1': '111', 'data2': '222' } } };
<script src="https://unpkg.com/vue"></script> <p id="example"> <parent></parent> </p> <script> var childNode = { template: '<p>{{myMessage}}的类型是{{type}}</p>', props: ['myMessage'], computed: { type() { return typeof this.myMessage } } } var parentNode = { template: ` <p class="parent"> <my-child my-message="1"></my-child> </p>`, components: { 'myChild': childNode } }; // 创建根实例 new Vue({ el: '#example', components: { 'parent': parentNode } }) </script>
Because it is a literal prop, its value is String
expressioncalculation How to convert String to number? In fact, you only need to change one place.
var parentNode = { template: ` <p class="parent"> //只要把父组件my-message="1"改成:my-message="1"结果就变成number类型 <my-child :my-message="1"></my-child> </p>`, };
var parentNode = { template: ` <p class="parent"> <my-child :my-message="data"></my-child> </p>`, components: { 'myChild': childNode }, //这里'data': 1代表就是number类型,'data': "1"那就代表String类型 data(){ return { 'data': 1 } } };
About the usage of $emit
1. The parent component can use props to pass data to the child component.2. Subcomponents can use $emit to trigger custom events of parent components.
Child primary key
<template> <p class="train-city"> <span @click='select(`大连`)'>大连</span> </p> </template> <script> export default { name:'trainCity', methods:{ select(val) { let data = { cityname: val }; this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件 } } } </script>
<template> <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //监听子组件的showCityName事件。 <template> <script> export default { name:'index', data () { return { toCity:"北京" } } methods:{ updateCity(data){//触发子组件城市选择-选择城市的事件 this.toCity = data.cityname;//改变了父组件的值 console.log('toCity:'+this.toCity) } } } </script>
<script src="https://unpkg.com/vue"></script> <p id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment1="incrementTotal"></button-counter> <button-counter v-on:increment2="incrementTotal"></button-counter> </p> <script> Vue.component('button-counter', { template: '<button v-on:click="increment">{{ counter }}</button>', //组件数据就是需要函数式,这样的目的就是让每个button-counter不共享一个counter data: function() { return { counter: 0 } }, methods: { increment: function() { //这里+1只对button的值加1,如果要父组件加一,那么就需要$emit事件 this.counter += 1; this.$emit('increment1', [12, 'kkk']); } } }); new Vue({ el: '#counter-event-example', data: { total: 0 }, methods: { incrementTotal: function(e) { this.total += 1; console.log(e); } } }); </script>
1:button-counter作为父主键,父主键里有个button按钮。
2:两个button都绑定了click事件,方法里: this.$emit('increment1', [12, 'kkk']);,那么就会去调用父类v-on所监听的increment1事件。
3:当increment1事件被监听到,那么执行incrementTotal,这个时候才会把值传到父组件中,并且调用父类的方法。
4:这里要注意第二个button-counter所对应的v-on:'increment2,而它里面的button所对应是this.$emit('increment1', [12, 'kkk']);所以第二个button按钮是无法把值传给他的父主键的。
示例:一个按钮点击一次那么它自身和上面都会自增1,而第二个按钮只会自己自增,并不影响上面这个。
还有就是第一个按钮每点击一次,后台就会打印一次如下:
四、ref ($refs)用法
ref 有三种用法
1.ref 加在普通的元素上,用this.ref.name 获取到的是dom元素
2.ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。
3.如何利用v-for 和ref 获取一组数组或者dom 节点
1.ref 加在普通的元素上,用this.ref.name 获取到的是dom元素
<script src="https://unpkg.com/vue"></script> <p id="ref-outside-component" v-on:click="consoleRef"> <component-father ref="outsideComponentRef"> </component-father> <p>ref在外面的组件上</p> </p> <script> var refoutsidecomponentTem = { template: "<p class='childComp'><h5>我是子组件</h5></p>" }; var refoutsidecomponent = new Vue({ el: "#ref-outside-component", components: { "component-father": refoutsidecomponentTem }, methods: { consoleRef: function() { console.log(this.); // #ref-outside-component vue实例 console.log(this.$refs.outsideComponentRef); // p.childComp vue实例 } } }); </script>
效果:当在p访问内点击一次:
2.ref使用在外面的元素上
<script src="https://unpkg.com/vue"></script> <!--ref在外面的元素上--> <p id="ref-outside-dom" v-on:click="consoleRef"> <component-father> </component-father> <p ref="outsideDomRef">ref在外面的元素上</p> </p> <script> var refoutsidedomTem = { template: "<p class='childComp'><h5>我是子组件</h5></p>" }; var refoutsidedom = new Vue({ el: "#ref-outside-dom", components: { "component-father": refoutsidedomTem }, methods: { consoleRef: function() { console.log(this); // #ref-outside-dom vue实例 console.log(this.$refs.outsideDomRef); // <p> ref在外面的元素上</p> } } }); </script>
效果:当在p访问内点击一次:
3.ref使用在里面的元素上---局部注册组件
<script src="https://unpkg.com/vue"></script> <!--ref在里面的元素上--> <p id="ref-inside-dom"> <component-father> </component-father> <p>ref在里面的元素上</p> </p> <script> var refinsidedomTem = { template: "<p class='childComp' v-on:click='consoleRef'>" + "<h5 ref='insideDomRef'>我是子组件</h5>" + "</p>", methods: { consoleRef: function() { console.log(this); // p.childComp vue实例 console.log(this.$refs.insideDomRef); // <h5 >我是子组件</h5> } } }; var refinsidedom = new Vue({ el: "#ref-inside-dom", components: { "component-father": refinsidedomTem } }); </script>
效果:当在click范围内点击一次:
4.ref使用在里面的元素上---全局注册组件
<script src="https://unpkg.com/vue"></script> <!--ref在里面的元素上--全局注册--> <p id="ref-inside-dom-all"> <ref-inside-dom-quanjv></ref-inside-dom-quanjv> </p> <script> //v-on:input指当input里值发生改变触发showinsideDomRef事件 Vue.component("ref-inside-dom-quanjv", { template: "<p class='insideFather'> " + "<input type='text' ref='insideDomRefAll' v-on:input='showinsideDomRef'>" + " <p>ref在里面的元素上--全局注册 </p> " + "</p>", methods: { showinsideDomRef: function() { console.log(this); //这里的this其实还是p.insideFather console.log(this.$refs.insideDomRefAll); // <input type="text"> } } }); var refinsidedomall = new Vue({ el: "#ref-inside-dom-all" }); </script>
效果:当我第一次输入1时,值已改变出发事件,当我第二次在输入时在触发一次事件,所以后台应该打印两次
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Summary of VueJs parent-child component communication methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement
