Table of Contents
Vue parent-child component
Vue parent-child component communication
Vue parent-to-child
{{ctitle}}
Vue Pass from son to parent
End of this chapter
Home Web Front-end Vue.js How to communicate between parent and child components in Vue? Let's talk about the methods of passing on from father to son and from son to father.

How to communicate between parent and child components in Vue? Let's talk about the methods of passing on from father to son and from son to father.

Nov 30, 2021 pm 07:41 PM
vue Parent-child component communication Component communication

How to communicate between parent and child components in Vue? The following article will take you to understand the communication between Vue parent and child components, and introduce the methods of parent passing value to child and child passing value to parent. I hope it will be helpful to everyone.

How to communicate between parent and child components in Vue? Let's talk about the methods of passing on from father to son and from son to father.

Vue parent-child component

What is a parent-child component?

Introduce another component into a component, and the introduced component is called a sub-component. Because of the modularization of Vue, the common parts will be extracted into a separate module, and all page content will not be included. Written in a vue file, due to modularity, communication problems between the two modules cannot be avoided. At this time, there is the problem of data transfer between modules (components). [Related recommendations: "vue.js Tutorial"]

Vue parent-child component communication

In vue, one component often uses the data of another component or Method, at this time there is a communication problem between parent and child components

Vue parent-to-child

1. Look at the code first, and explain it below

<body>
//父组件
<div id="app">
    <cpn3 :ctitle="title"></cpn3>
</div>
//子组件
<template id="cpn3">
    <div>
        <h1 id="ctitle">{{ctitle}}</h1>
        <p>orange</p>
    </div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
    //子组件
    Vue.component("cpn3", {
        template: "#cpn3",
        // 组件里的data是一个函数,必须要返回一个对象,变量写在返回对象里
        props: {
            ctitle: {
                type: String,
                default () {
                    return {}
                }
            }
        }
    })
	//父组件
    const app = new Vue({
        el: "#app",
        data: {
            title: &#39;orange&#39;
        },
        methods: {},

    })
</script>
</body>
Copy after login

Explanation:
1. First write the basic template separation component

2. Add props attributes to the sub-component in object mode. In the props, you can write the parameters you need to pass. The parameters are also in object mode. Code It’s clearer,

    //子组件
    Vue.component("cpn3", {
        template: "#cpn3",
        // 组件里的data是一个函数,必须要返回一个对象,变量写在返回对象里
        props: {
            ctitle: {
            //参数也使用对象形式,type传类型  default函数,是在找不到参数时返回一个值显示
                type: String,
                default () {
                    return {}
                }
            }
        }
    })
Copy after login

2. Then add the required attributes to the parent component

//父组件
    const app = new Vue({
        el: "#app",
        data: {
        //这里的title就是要传入子组件的属性  在父组件中定义
            title: &#39;orange&#39;
        },
        methods: {},

    })
Copy after login

3. Bind two parameters to the parent component

 <div id="app">
	//可以理解为将父组件中title 赋值给 ctitle,这样子组件就可以使用父组件的data属性了
    <cpn3 :ctitle="title"></cpn3>
</div>
Copy after login

4. Finally In the sub-component, use the property name defined by the sub-component

//子组件
<template id="cpn3">
    <div>
    //这里的属性名为ctitle
        <h1 id="ctitle">{{ctitle}}</h1>
    </div>
</template>
Copy after login

Vue Pass from son to parent

1. Pass from son to parent means,, sub-component The content is passed to the parent component, so that the parent component can use the data from the child component at any time. The usage method is: Custom function

#1. First, let’s make an imitation Taobao sidebar product. Click or move the mouse to the above to display the content product case

How to communicate between parent and child components in Vue? Lets talk about the methods of passing on from father to son and from son to father.

2. Taking the above picture as an example, let’s talk about the child-to-father transmission of components

2.1 Let’s separate the sub-component and the parent component. Let’s talk about them one by one. Let’s first look at the sub-component code

<!-- 子组件 -->
<template id="cpn">
    <div>
        <h1 id="ctitle">{{ctitle}}</h1>
        <button v-for="item in list" @click="goodsclick(item)">{{item.name}}</button>
    </div>
</template>
<script>
Vue.component("cpn", {
        template: &#39;#cpn&#39;,
        //父传子 props   
        props: {
            ctitle: {
                type: String,
                //找不到数据时
                default () {
                    return {}
                }
            }
        },
        data() {
            return {
                list: [{
                    id: &#39;phone&#39;,
                    name: &#39;手机&#39;
                }, {
                    id: &#39;tv&#39;,
                    name: &#39;电视&#39;
                }, {
                    id: &#39;p&#39;,
                    name: &#39;家电&#39;
                }, {
                    id: &#39;computer&#39;,
                    name: &#39;电脑&#39;
                }, ]
            }
        },
        //子传父 自定义事件
        methods: {
            // 自定义事件
            goodsclick(item) {
                this.$emit(&#39;itemclick&#39;, item)
            }
        }
    })
    </script>
Copy after login

Explanation: The sub-component is to write a component (html) and wrap it up , and can be used at any time, which is equivalent to HTML, just packaged (this understanding should be no problem)

1. Subcomponents have data, methods, and attributes like vue. So write an array in data, and then use v-for to traverse and generate buttons There is no difference from normal writing, then write a function, bind the click event, and pass the item, which is the object passed in the array, into the function,

<button v-for="item in list" @click="goodsclick(item)">{{item.name}}</button>
Copy after login

2. Then the most important and critical step comes , that is, in the click event function you bound, send a custom function to the parent component, that is, send it to the parent component

methods: {
            // 自定义事件
            goodsclick(item) {
            //itemclick就是自定义函数,并且将item也传过去给父组件
                this.$emit(&#39;itemclick&#39;, item)
            }
        }
Copy after login

How to communicate between parent and child components in Vue? Lets talk about the methods of passing on from father to son and from son to father.

#This is when the child component is written, this It is the style of the child component, as shown in the picture above

2. Next, let’s talk about how the parent component receives the custom event from the child component

<!-- 父组件 -->
<div id="app">
    <cpn :ctitle="title" @itemclick="cpnclick"></cpn>
</div>
<script>
//父组件    
    const app = new Vue({
        el: "#app",
        data: {
            title: "title",
        },
        methods: {
            cpnclick(item) {
                console.log("cpnclick", item);
            }
        }
    })
</script>
Copy after login

Explain: After you write the subcomponent, you need to call it. The call is just your component name as the label. Here is

<cpn :ctitle="title" @itemclick="cpnclick"></cpn>
Copy after login

Write a function in the parent component and bind the self passed from the subcomponent in it. Define the event, so that the sub-component is successfully bound, so that the sub-component transfers data to the parent component.

End of this chapter

For more programming-related knowledge, please visit:Introduction to Programming ! !

The above is the detailed content of How to communicate between parent and child components in Vue? Let's talk about the methods of passing on from father to son and from son to father.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles