search
HomeWeb Front-endJS TutorialSummary 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></script>
<p>
 <parent></parent>
</p>
<script>
 //要想子组件能够获取父组件的,那么在子组件必须申明:props
 var childNode = {
  template: &#39;<p>{{message}}&#39;,
  props: [&#39;message&#39;]
 }
 //这里的message要和上面props中值一致
 var parentNode = {
  template: `
   <p class="parent">
   <child message="我是">
   <child message="徐小小">
   `,
  components: {
   &#39;child&#39;: childNode
  }
 };
 // 创建根实例
 new Vue({
  el: &#39;#example&#39;,
  components: {
   &#39;parent&#39;: 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可以写成[&#39;my-message&#39;]或者[&#39;myMessage&#39;]都是可以的
 //但是template里的属性名,只能是驼峰式{{myMessage}},如果也写成{{my-message}}那么是无效的
 var childNode = {
  template: &#39;<p>{{myMessage}}&#39;,
  props: [&#39;myMessage&#39;]
 }
 //这里的属性名为my-message
 var parentNode = {
  template: `
   <p class="parent">
   <child my-message="我是">
   <child my-message="徐小小">
   `,
  components: {
   &#39;child&#39;: 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: &#39;<p>{{myMessage}}的类型是{{type}}&#39;,
  props: [&#39;myMessage&#39;],
  computed: {
   type() {
    return typeof this.myMessage
   }
  }
 }
 var parentNode = {
  template: `
 <p class="parent">
 <my-child my-message="1">
 `,
  components: {
   &#39;myChild&#39;: childNode
  }
 };
 // 创建根实例
 new Vue({
  el: &#39;#example&#39;,
  components: {
   &#39;parent&#39;: parentNode
  }
 })
</script>
Result:

Because it is a literal prop, its value is String

"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

expressioncalculation 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:&#39;trainCity&#39;, 
 methods:{ 
 select(val) { 
  let data = { 
  cityname: val 
  }; 
  this.$emit(&#39;showCityName&#39;,data);//select事件触发后,自动触发showCityName事件 
 } 
 } 
} 
</script>
Parent component

<template> 
 <traincity></traincity> //监听子组件的showCityName事件。 
<template> 
<script> 
export default { 
 name:&#39;index&#39;, 
 data () { 
 return { 
  toCity:"北京" 
 } 
 } 
 methods:{ 
 updateCity(data){//触发子组件城市选择-选择城市的事件 
  this.toCity = data.cityname;//改变了父组件的值 
  console.log(&#39;toCity:&#39;+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(&#39;button-counter&#39;, {
  template: &#39;<button v-on:click="increment">{{ counter }}&#39;,
  //组件数据就是需要函数式,这样的目的就是让每个button-counter不共享一个counter
  data: function() {
   return {
    counter: 0
   } 
  },
  methods: {
   increment: function() {
   //这里+1只对button的值加1,如果要父组件加一,那么就需要$emit事件
    this.counter += 1;
    this.$emit(&#39;increment1&#39;, [12, &#39;kkk&#39;]);
   }
  }
 });
 new Vue({
  el: &#39;#counter-event-example&#39;,
  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=&#39;childComp&#39;><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=&#39;childComp&#39;><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=&#39;childComp&#39; v-on:click=&#39;consoleRef&#39;>" +
   "<h5 ref=&#39;insideDomRef&#39;>我是子组件" +
   "",
  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=&#39;insideFather&#39;> " +
   "<input type=&#39;text&#39; ref=&#39;insideDomRefAll&#39; v-on:input=&#39;showinsideDomRef&#39;>" +
   " <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中文网其它相关文章!

推荐阅读:

怎样用JS跨域实现POST

怎么用Vue实现树形视图数据

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different 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 WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript'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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.