加载中......
输入验证码,即可复制
微信扫码下载好向圈APP, 登陆后即可进入消息页面查看验证码
只需要3秒时间
Vue 3学习:8. 父子组件通信-1.jpg

在Vue 3中父子组件间的通信依然可以使用provide/inject来实现。

token

在Vue 3中,使用provide/inject,需要先创建一个Symbol类型的token:
<template>    <div>This is Father</div>    <div>        <h3>child slot</h3>        <slot></slot>    </div></template><script lang="ts">    import { defineComponent, provide, ref } from 'vue';    import { TOKEN_FATHER } from './token';    export default defineComponent({        name: 'Father',        setup() {            const father = ref('我是父组件');            let count = 1;            setInterval(() => {                father.value = `我是父组件-${count}`;                count++;            }, 500);            provide(TOKEN_FATHER, father);            return {};        }    });</script>

父组件

创建父组件,内容如下:
<template>    <div>This is Child, the father is : {{ father }}</div></template><script lang="ts">    import { defineComponent, inject } from 'vue';    import { TOKEN_FATHER } from './token';    export default defineComponent({        name: 'Child',        setup() {            const father = inject(TOKEN_FATHER);            return {                father            };        }    });</script><style scoped></style>
在父组件中,使用provide为前面创建的额token绑定一个响应是的变量:father。通过setInterval方法,每500毫秒修改一次father的值。

子组件

创建子组件,内容如下:
<template>    <div>This is Child, the father is : {{ father }}</div></template><script lang="ts">    import { defineComponent, inject } from 'vue';    import { TOKEN_FATHER } from './token';    export default defineComponent({        name: 'Child',        setup() {            const father = inject(TOKEN_FATHER);            return {                father            };        }    });</script><style scoped></style>
在子组件中,通过inject方式注入目标token,将注入的father变量提供给模板使用。

效果


Vue 3学习:8. 父子组件通信-2.jpg

总结

使用provide/inject可以很方便的就实现父组件向子组件传输数据,实现方式和Vue 2的时候略有不同。


个人公众号:Java码农
程序员圈
12443 查看 0 0 反对

说说我的看法高级模式

您需要登录后才可以回帖 登录|立即注册

还没人评论此主题哦

相关阅读