Web Front-end
JS Tutorial
Summary of parent-child mutual communication methods in VueJs componentsSummary of parent-child mutual communication methods in VueJs components
This time I will bring you a summary of the mutual communication methods between father and son in the VueJs component. What are the precautions for mutual communication between the father and the son in the VueJs component. 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: PropsPass from child to parent: Child: $emit(eventName) Parent $on(eventName)
Parent accesses child: ref
Let’s explain the three cases below:
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 props1, static props<script></script>
<p>
<parent></parent>
</p>
<script>
//要想子组件能够获取父组件的,那么在子组件必须申明:props
var childNode = {
template: '<p>{{message}}',
props: ['message']
}
//这里的message要和上面props中值一致
var parentNode = {
template: `
<p class="parent">
<child message="我是">
<child message="徐小小">
`,
components: {
'child': childNode
}
};
// 创建根实例
new Vue({
el: '#example',
components: {
'parent': parentNode
}
})
</script> Effect:
## Naming convention:
For attributes declared by props, in the parent HTML template, the attribute name It is necessary to use the dash writing method
When the child props attribute is declared, you can use the small camel case or the dash writing method; when the child template uses variables passed from the parent, you need to use the corresponding small camel case Writing method
What does the above sentence mean?
<script>
//这里需要注意的是props可以写成['my-message']或者['myMessage']都是可以的
//但是template里的属性名,只能是驼峰式{{myMessage}},如果也写成{{my-message}}那么是无效的
var childNode = {
template: '<p>{{myMessage}}',
props: ['myMessage']
}
//这里的属性名为my-message
var parentNode = {
template: `
<p class="parent">
<child my-message="我是">
<child my-message="徐小小">
`,
components: {
'child': childNode
}
};
</script>
If myMessage in our childNode is changed to {{my-message}}, look at the running results:
2. Dynamic props
In the template, you need to dynamically bind the data of the parent component to the props of the child template, which is similar to binding to any ordinary HTML feature, that is, use v-bind. Whenever the data of the parent component changes, the change will also be transmitted to the child component
var childNode = {
template: '<p>{{myMessage}}</p>',
props: ['my-message']
}
var parentNode = {
template: `
<p>
<child></child>
<child></child>
</p>`,
components: {
'child': childNode
},
data() {
return {
'data1': '111',
'data2': '222'
}
}
};
3. Passing numbers
A common mistake beginners make is to use literal syntax to pass values
<script></script>
<p>
<parent></parent>
</p>
<script>
var childNode = {
template: '<p>{{myMessage}}的类型是{{type}}',
props: ['myMessage'],
computed: {
type() {
return typeof this.myMessage
}
}
}
var parentNode = {
template: `
<p class="parent">
<my-child my-message="1">
`,
components: {
'myChild': childNode
}
};
// 创建根实例
new Vue({
el: '#example',
components: {
'parent': parentNode
}
})
</script>
Result:
Because it is a literal prop, its value isString
"1" instead of number. If you want to pass an actual number, you need to use v-bind so that its value is treated as a JS
calculation How to convert String to number? In fact, you only need to change one place. var parentNode = {
template: `
<p>
//只要把父组件my-message="1"改成:my-message="1"结果就变成number类型
<my-child></my-child>
</p>`,
}; Of course, if you want to pass a string type through v-bind, what should you do?
We can use dynamic props and set the corresponding number in the data attribute 1
var parentNode = {
template: `
<p>
<my-child></my-child>
</p>`,
components: {
'myChild': childNode
},
//这里'data': 1代表就是number类型,'data': "1"那就代表String类型
data(){
return {
'data': 1
}
}
};
3. Transfer from child to parent: $emit
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>
<span>大连</span>
</p>
</template>
<script>
export default {
name:'trainCity',
methods:{
select(val) {
let data = {
cityname: val
};
this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件
}
}
}
</script>
Parent component
<template>
<traincity></traincity> //监听子组件的showCityName事件。
<template>
<script>
export default {
name:'index',
data () {
return {
toCity:"北京"
}
}
methods:{
updateCity(data){//触发子组件城市选择-选择城市的事件
this.toCity = data.cityname;//改变了父组件的值
console.log('toCity:'+this.toCity)
}
}
}
</script></template></template>
The result is: toCity: Dalian
Second case
<script></script>
<p>
</p><p>{{ total }}</p>
<button-counter></button-counter>
<button-counter></button-counter>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}',
//组件数据就是需要函数式,这样的目的就是让每个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>
Detailed explanation:
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></script>
<p>
<component-father>
</component-father>
</p><p>ref在外面的组件上</p>
<script>
var refoutsidecomponentTem = {
template: "<p class='childComp'><h5>我是子组件"
};
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></script>
<!--ref在外面的元素上-->
<p>
<component-father>
</component-father>
</p><p>ref在外面的元素上</p>
<script>
var refoutsidedomTem = {
template: "<p class='childComp'><h5>我是子组件"
};
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在外面的元素上
}
}
});
</script>
效果:当在p访问内点击一次:

3.ref使用在里面的元素上---局部注册组件
<script></script>
<!--ref在里面的元素上-->
<p>
<component-father>
</component-father>
</p><p>ref在里面的元素上</p>
<script>
var refinsidedomTem = {
template: "<p class='childComp' v-on:click='consoleRef'>" +
"<h5 ref='insideDomRef'>我是子组件" +
"",
methods: {
consoleRef: function() {
console.log(this); // p.childComp vue实例
console.log(this.$refs.insideDomRef); // <h5 >我是子组件
}
}
};
var refinsidedom = new Vue({
el: "#ref-inside-dom",
components: {
"component-father": refinsidedomTem
}
});
</script>
效果:当在click范围内点击一次:

4.ref使用在里面的元素上---全局注册组件
<script></script>
<!--ref在里面的元素上--全局注册-->
<p>
<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在里面的元素上--全局注册 " +
"",
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 parent-child mutual communication methods in VueJs components. For more information, please follow other related articles on the PHP Chinese website!
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.





