How to implement communication between vue parent and child components
This time I will show you how to implement communication between vue parent and child components, and what are the precautions to implement communication between vue parent and child components. The following is a practical case, let's take a look.
Components are one of the most powerful features of vue.js, and the scopes of component instances are independent of each other, which means that data between different components cannot reference each other. Then how to communicate between components has become a key knowledge in Vue. This article will explain how to implement communication between parent and child components through the knowledge points of props, $ref and $emit. Before talking about how to implement communication, let's first build two components father.vue and child.vue as the basis of the example.//父组件 <template> <p> </p> <h1 id="我是父组件">我是父组件!</h1> <child></child> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, } </script>
//子组件 <template> <h3 id="我是子组件">我是子组件!</h3> </template> <script> </script>The codes in these two parts are very clear. The parent component imports the child component through import and registers it in the components attribute. Then the child component can be embedded in the parent using the tag
1. Communication through prop
The props option of the child component can receive data from the parent component. That's right, it can only be received. Props are one-way bound, that is, they can only be passed from the parent component to the child component, not the other way around. The delivery methods are also divided into two types:(1) Static delivery
The child component declares a custom attribute through the props option, and then the parent component You can pass data to subcomponents through this attribute when nesting tags.<!-- 父组件 --> <template> <p> </p> <h1 id="我是父组件">我是父组件!</h1> <child></child> //通过自定义属性传递数据 </template> <script> import Child from '../components/child.vue' export default { components: {Child}, } </script>
<!-- 子组件 --> <template> <h3 id="message">{{message}}</h3> </template> <script> export default { props: ['message'] //声明一个自定义的属性 } </script>
(2) Dynamic transfer
We already know that we can pass a static value to props as above, but in more cases we need dynamic data. This can be achieved using v-bind. By binding custom properties of props through v-bind, what is passed is not a staticstring, it can be an expression, Boolean value, object, etc. any type of value.
<!-- 父组件 --> <template> <p> </p> <h1 id="我是父组件">我是父组件!</h1> <child></child> <!-- 这是一个 JavaScript 表达式而不是一个字符串。--> <child></child> <!-- 用一个变量进行动态赋值。--> <child></child> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, data() { return { a:'我是子组件二!', b:112233, msg: '我是子组件三!'+ Math.random() } } } </script>
<!-- 子组件 --> <template> <h3 id="message">{{message}}</h3> </template> <script> export default { props: ['message'] } </script>The effect is like this:
2. Implemented through $ref Communication
The official explanation for ref is: ref is used to register reference information for elements or subcomponents. Reference information will be registered on the $refs object of the parent component. Can’t understand, right? It's normal, I can't understand it either. How should that be understood? Take a look at my explanation:- If ref is used on a subcomponent, it points to the component instance, which can be understood as the index of the subcomponent. It is possible to obtain the subcomponent through $ref.
Properties and methods defined in.
- If ref is used on an ordinary DOM element, the reference points to the DOM element. Through $ref, it is possible to obtain the attribute collection of the DOM and easily access the DOM element. The function is the same as JQ Selectors are similar.
<!-- 父组件 --> <template> <p> </p> <h1 id="我是父组件">我是父组件!</h1> <child></child> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, mounted: function () { console.log( this.$refs.msg); this.$refs.msg.getMessage('我是子组件一!') } } </script>
<!-- 子组件 --> <template> <h3 id="message">{{message}}</h3> </template> <script> export default { data(){ return{ message:'' } }, methods:{ getMessage(m){ this.message=m; } } } </script>From the above code, we can find that through ref='msg', the instance of the subcomponent child can be pointed to $ref, and through .msg.getMessage() calls the getMessage method of the subcomponent and passes the parameters to the subcomponent. The following is the content printed by "console.log( this.$refs.msg);", which can give everyone a better understanding of what we get through ref:
- prop focuses on the transfer of data, it cannot call properties and methods in subcomponents. For usage scenarios such as customizing the title and content when creating an article component, prop is most suitable for use.
$ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。
3.通过$emit 实现通信
上面两种示例主要都是父组件向子组件通信,而通过$emit 实现子组件向父组件通信。
对于$emit官网上也是解释得很朦胧,我按我自己的理解是这样的:
vm.$emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
<template> <p> </p> <h1 id="title">{{title}}</h1> <child></child> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, data(){ return{ title:'' } }, methods:{ showMsg(title){ this.title=title; } } } </script>
<template> <h3 id="我是子组件">我是子组件!</h3> </template> <script> export default { mounted: function () { this.$emit('getMessage', '我是父组件!') } } </script>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to implement communication between vue parent and child components. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

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.

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