Vue grandchildren component pass value

  • $attrs is used to pass data from grandparents to grandchildren.
  • $listeners are used to trigger events in grandparent components from grandchildren.

Use of $attrs:

  1. In the father component (index.vue), similar to props passing value, bind the value that needs to be passed to the parent component.
  2. In the parent component, it is also similar to passing values ​​through props, but what is passed here is not the value, but $attrs.
  3. In the grandchild component, receive props, so that this data can be used in the grandchild component. (It should be noted that there is no need to receive props in the parent component, as long as it is received in the grandson component.)

Then the code:


 

//index.vue:
<Father :homeInfo="homeInfo"/>

//Father.vue:
<Son v-bind="$attrs"/>

//son.vue:
<template>
    <div class="home">
    {
   
   {homeInfo.name}}
    </div>
</template>

<script>
export default {
    name: "Son",
    data() {
        return {};
    },
    props: {
        homeInfo: {
            default: Object,
            default: () => {},
        },
    },
};
</script>

Use of $listeners:

  1. In the father component (index.vue), bind the event.
  2. In the parent component, it is similar to binding events, but what is bound here is not a specific event, but an event v-on="$listeners".
  3. In the grandchildren component, trigger ( $emit) this event when needed. Then the code:

//index.vue:
<Father :homeInfo="homeInfo" @update="update"/>

//Father.vue:
<Son v-bind="$attrs" v-on="$listeners"/>

//son.vue:
<template>
    <div class="home" @click="update">
    {
   
   {homeInfo.name}}
    </div>
</template>

<script>
export default {
    name: "Son",
    data() {
        return {};
    },
    props: {
        homeInfo: {
            default: Object,
            default: () => {},
        },
    },
    methods: {
        update() {
            const newHome = {
                name: 'new'
            }
            this.$emit("update", newHome)
        }
    }
};
</script>

Summarize:

In fact $attrs, $listenersthe equivalent is a transit, mainly used in the parent component. Grandfather and grandson components can keep the previous use!

Guess you like

Origin blog.csdn.net/YZ_ZZZ24/article/details/126075551