在Vue 3中父子组件间的通信依然可以使用/来实现。
token
在Vue 3中,使用/,需要先创建一个类型的token:
This is Father
child slot
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 {};
}
});
父组件
创建父组件,内容如下:
This is Child, the father is : {{ father }}
import { defineComponent, inject } from 'vue';
import { TOKEN_FATHER } from './token';
export default defineComponent({
name: 'Child',
setup() {
const father = inject(TOKEN_FATHER);
return {
father
};
}
});
在父组件中,使用为前面创建的额token绑定一个响应是的变量:。通过方法,每500毫秒修改一次的值。
子组件
创建子组件,内容如下:
This is Child, the father is : {{ father }}
import { defineComponent, inject } from 'vue';
import { TOKEN_FATHER } from './token';
export default defineComponent({
name: 'Child',
setup() {
const father = inject(TOKEN_FATHER);
return {
father
};
}
});
在子组件中,通过方式注入目标token,将注入的变量提供给模板使用。
效果
总结
使用/可以很方便的就实现父组件向子组件传输数据,实现方式和Vue 2的时候略有不同。
———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,永久会员只需109元,全站资源免费下载 点击查看详情
站 长 微 信: nanadh666
声明:1、本内容转载于网络,版权归原作者所有!2、本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。3、本内容若侵犯到你的版权利益,请联系我们,会尽快给予删除处理!