创建父组件,内容如下:
<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变量提供给模板使用。