在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变量提供给模板使用。
效果
总结
使用provide/inject可以很方便的就实现父组件向子组件传输数据,实现方式和Vue 2的时候略有不同。
个人公众号:Java码农