在Vue中我们可以使用Inject和Provided来完成爷孙组件的直接通信
动态效果可拷贝下面代码实现

我们在爷组件使用Provided将数据提供出去,在孙组件中使用Inject接收数据使用
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>lesson 41title>
<script src="https://unpkg.com/vue@next">script>
head>
<body>
<div id="root">div>
body>
<script>
// provide, inject
// dom ref
// const app = Vue.createApp({
// setup() {
// const { provide, ref, readonly } = Vue;
// const name = ref('dell');
// provide('name', readonly(name));
// provide('changeName', (value) => {
// name.value = value;
// });
// return { }
// },
// template: `
//
//
//
// `,
// });
// app.component('child', {
// setup() {
// const { inject } = Vue;
// const name = inject('name');
// const changeName = inject('changeName');
// const handleClick = () => {
// changeName('lee');
// }
// return { name, handleClick }
// },
// template: '{{name}}'
// })
// CompositionAPI 的语法下,获取真实的 DOM 元素节点
const app = Vue.createApp({
setup() {
const { ref, onMounted } = Vue;
const hello = ref(null);
onMounted(() => {
console.log(hello.value);
})
return { hello }
},
template: `
hello world
`,
});
const vm = app.mount('#root');
script>
html>