Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第74题:谈谈你对provide和inject的理解? #74

Open
noxussj opened this issue Jun 18, 2020 · 0 comments
Open

第74题:谈谈你对provide和inject的理解? #74

noxussj opened this issue Jun 18, 2020 · 0 comments
Labels

Comments

@noxussj
Copy link
Owner

noxussj commented Jun 18, 2020

通过provide/inject可以轻松实现跨级访问祖先组件的数据

栗子

父组件 index.vue

<template>
    <!-- 父组件 -->
    <div class="views__home">
        <my-children></my-children>
    </div>
</template>

<script>
import MyChildren from './my-children.vue'; // 子组件

export default {
    components: {
        MyChildren
    },
    provide() {
        return {
            student: {
                name: 'xiaoming'
            }
        };
    },
    mounted() {
        console.log(this.student); // undefined
    }
};
</script>

子组件 my-children.vue

<template>
    <!-- 子组件 -->
    <div class="views__home__my-children">
        <my-grandson></my-grandson>
    </div>
</template>

<script>
import MyGrandson from './my-grandson.vue'; // 孙组件
export default {
    components: {
        MyGrandson
    }
};
</script>

孙组件 my-grandson.vue

<template>
    <!-- 孙组件 -->
    <div class="views__home__my-grandson"></div>
</template>


<script>
export default {
    inject: ['student'],
    mounted() {
        console.log(this.student); // { name : 'xiaoming' }
    }
};
</script>

可以看出来 my-grandson组件可以直接获取到 index组件传过来的变量,中间不在需要经过 my-children组件

@noxussj noxussj added the Vue label Jun 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant