17、Vue 3 (2024 版)基础笔记 - 跨组件数据传递与依赖注入

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 77

时间: 2024-05-18 23:40:04

有 app、parent、child 三个组件,其中数据是在 app 组件中,那么 child 组件如何获取 app 组件中定义的数据?此时,可以使用数据提供与依赖注入实现。

依赖注入可以实现跨组件传递数据,仅支持“高到低”的传递,使用如下:

  • 1、高层组件使用:import { provide } from 'vue';
  • 2、父级组件使用:provide('key', data)
  • 3、儿孙组件使用:import {inject} from 'vue'
1、app 组件中定义数据

src/App.vue

<template>
    <h3>组件间传值与依赖注入</h3>
    <div class="app">
        <h2>{{  username }}</h2>
        <h2>{{  userinfo }}</h2>
    </div>

    <ParentDemo></ParentDemo>
</template>

<script setup lang="ts">
    // 步骤一:引入 provide
    import { ref, provide } from 'vue';
    import ParentDemo from './components/ParentDemo.vue'

    const username = ref('王丽丽')
    const userinfo = ref({
        username: '王美丽',
        age: 19
    })

    // 步骤二:使用 provide 提供跨组件使用的数据
    provide('username', username)
    provide('userinfo', userinfo)

</script>

<style scoped>
    .app {
        background: lightgray;
    }
</style>
2、parent 组件中引入 child 组件

src/components/ParentDemo.vue

<template>
    <div class="parent">
        <h2>Parent 组件</h2>
        <!-- 步骤三:父组件中使用子组件 -->
        <ChildDemo></ChildDemo>
    </div>

</template>

<script setup lang="ts">
    import ChildDemo from './ChildDemo.vue';
</script>

<style scoped>
    .parent {
        background: lightblue;
        padding: 30px;
    }
</style>
3、子组件中使用 inject 使用 app 组件数据

src/components/ChildDemo.vue

<template>
    <div class="child">
        <h2>Child 组件</h2>
        <!-- 步骤六:使用数据 -->
        <p>{{  username }}</p>
        <p>{{  userinfo }}</p>
    </div>
</template>

<script setup lang="ts">
    // 步骤四:引入 inject
    import {inject} from 'vue'

    // 步骤五:使用 inject 接收 app 组件中的数据
    const username = inject('username')
    const userinfo = inject('userinfo')
</script>

<style scoped>
    .child {
        background: pink;
        padding: 60px;
    }
</style>
请登录后再评论