Table of Contents
1. Pass parent component to child component" >1. Pass parent component to child component
" >2. A brief discussion on Props
当前计数:{{counter}}
Home Web Front-end Vue.js A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)

A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)

Nov 08, 2022 pm 08:25 PM
vue components Component communication

How to communicate between parent and child components in

Vue? The following article will introduce to you the methods of father to son and son to father. I hope it will be helpful to you!

A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)

1. Pass parent component to child component

⭐⭐

  • Parent component is passed to the child component: through the props attribute; [Related recommendations: vuejs video tutorial, web front-end development]
  • The child component is passed to the parent component: Trigger the event through $emit;
    made by 森姐

## Here we know that the parent component has some data that needs to be displayed by the child component, then we can pass
propsTo complete the communication between components

To complete the communication between components through props

A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)
A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)

2. A brief discussion on Props

⭐⭐

So what are
Props?

    Function: Accept the properties passed by the parent component
  • Props means you can register some custom attributes on the component;
  • The parent component assigns values ​​to these attributes (attributes), and the child component obtains the corresponding value through the name of the attribute;
In a single-file component using

script setup, props You can use the defineProps() macro to declare:

1

2

3

4

5

<script>

const props = defineProps([&#39;foo&#39;])

 

console.log(props.foo)

</script>

Copy after login

1) The array type

is not used ## In the component of #script setup

, prop can be declared using the props option: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">export default {   props: ['foo'],   setup(props) {     // setup() 接收 props 作为第一个参数     console.log(props.foo)   } }</pre><div class="contentsignin">Copy after login</div></div>Example, use of object syntax

  • App.vue

    uses components and attributes defined by integer props

    1

    2

    3

    <template>

        <show-info></show-info>

    </template>

    Copy after login
    ##showInfo.vue
  • Subcomponent

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

     export default {

            props:{

                name :{

                    type:String,

                    default:"我是默认值name"

                },

                height:{

                    type:Number,

                    default:2

                }

            }

        }

    Copy after login
    Also:
  • So what types of types can be?


String

    Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol
  • 2) Object type

is declared in the form of object

props (This is quite commonly used) Use script setup

1

2

3

4

defineProps({

  title: String,

  likes: Number

})

Copy after login
non-script setup

1

2

3

4

5

6

export default {

  props: {

    title: String,

    likes: Number

  }

}

Copy after login
3. The child component is passed to the parent component

⭐⭐ The child component is passed to the parent component and the event is triggered through $emit


The child component passes content to the parent component: A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass from son to father)

When some events occur in the child component, such as a click in the component, the parent component needs to switch content;

    When the child component has some content that you want to pass to the parent component;
  • $emit(“add”, count)
  • The first parameter is the customized event name, and the second parameter It is the passed parameter

⭐⭐
Take a counter case


Here we have two sub-components and a parent component

    The sub-component is defined in The name of the event triggered in some cases
  • In the parent component, pass in the name of the event to be monitored in the form of v-on (syntactic sugar @), and bind it to the corresponding method;
  • Finally, when an event occurs in the child component, the corresponding event is triggered according to the event name
  • 1) Parent component
  • App.vue

The parent component listens to the addition or subtraction events of the child component, and the parent component listens to the event through the child component

    The parent component listens to the custom event emitted by the child component, and then performs the corresponding operation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<template>

    <div>

    <h2 id="当前计数-counter">当前计数:{{counter}}</h2>

    <!-- 1.自定义add-counter 并且监听内部的add事件 -->

   <add-counter></add-counter>  

   <!-- 2.自定义su-counter组件,监听内部的sub事件 -->

   <sub-counter></sub-counter>

   </div>

</template>

<script>

import AddCounter from &#39;./AddCounter.vue&#39;

import SubCounter from &#39;./SubCounter.vue&#39;

    export default {

  components: {

    AddCounter,

    SubCounter

 },

    data() {

        return {

            counter:0

        }

    },

    methods:{

        addBtnClick(count) {

            this.counter += count

        },

        subBtnClick(count) {

            this.counter -= count

        }

    }

}

</script>

Copy after login
  • 2) Subcomponent 1
  • AddCounter.vue

    What is defined here is the addition operation of the counter
    After the subcomponent event is triggered, through this.$emit The way to emit events

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    <template>

        <div>

            <button>+1</button>

            <button>+5</button>

            <button>+10</button>

        </div>

    </template>

    <script>

        export default {

            methods:{

                btnClick(count) {

                    // 让子组件发出去一个自定义事件

                    // 第一个参数自定义的事件名称,第二个参数是传递的参数

                    this.$emit("add",count)

                }

            }

        }

    </script>

    Copy after login

    3) Subcomponent 2
    SubCounter.vue

    What is defined here is the decrement operation of the counter

    Subcomponent event triggering After that, the event is issued through

    this.$emit

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    <template>

        <div>

            <button>-1</button>

            <button>-5</button>

            <button>-10</button>

        </div>

    </template>

    <script>

        export default {

            // 1.emits数组语法

           emits:["addd"],

           methods:{

            btnClick(count) {

                this.$emit("sub",count)

            }

           }

        }

    </script>

    Copy after login
    This case is very classic, you can think about it again and again~ (Learning video sharing:

    Programming Basic video

    )

    The above is the detailed content of A brief analysis of how to communicate between parent and child components in Vue (pass from father to son|pass 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

    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 ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

    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.

    What does it mean to lazy load vue? What does it mean to lazy load vue? Apr 07, 2025 pm 11:54 PM

    In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using &lt;keep-alive&gt; and &lt;component is&gt; components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

    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.

    Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

    Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

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

    See all articles