祖组件
<template>
<div class="text">
测试 piano或者inject测试index
{{ menuVisible }}
<Parent />
</div>
</template>
<script>
import {
defineComponent,
getCurrentInstance,
reactive,
provide,
ref,
} from "vue";
import Parent from "@/views/ceShi/modules/parent.vue";
export default defineComponent({
name: "",
// 注册你的组件
components: { Parent },
emits: {},
setup(props, { attrs, slots, emit, expose }) {
const menuVisible = ref(true);
provide("menuVisible", menuVisible);
return {
menuVisible,
attrs, // Attribute (非响应式对象,等同于 attrs),有状态,会随组件本身的更新而更新
slots,
emit, // 触发事件 (方法,等同于 emit)
expose, // 暴露公共 property (函数)
};
},
methods: {},
});
</script>
<style lang="scss" scoped>
.text {
color: #ccc;
}
</style>
父组件
<template>
<div class="parent">
parent{{ menuVisible }}
<Children />
<!-- <button @click="toggle">点击父组件切换</button> -->
</div>
</template>
<script>
import {
defineComponent,
getCurrentInstance,
reactive,
ref,
inject,
} from "vue";
import Children from "@/views/ceShi/modules/children.vue";
export default defineComponent({
name: "",
// 注册你的组件
components: { Children },
props: {},
emits: {},
setup(props, { attrs, slots, emit, expose }) {
const menuVisible = inject("menuVisible");
return {
menuVisible,
attrs, // Attribute (非响应式对象,等同于 attrs),有状态,会随组件本身的更新而更新
slots,
emit, // 触发事件 (方法,等同于 emit)
expose, // 暴露公共 property (函数)
};
},
methods: {},
});
</script>
<style lang="scss" scoped></style>
孙子组件
<template>
<div class="children">
children
{{ menuVisibleChildren }}
<!-- {{ menuVisible }} -->
<button @click="togal">点击切换</button>
</div>
</template>
<script>
import {
defineComponent,
getCurrentInstance,
reactive,
ref,
inject,
} from "vue";
export default defineComponent({
name: "",
// 注册你的组件
components: {},
props: {},
emits: {},
setup(props, { attrs, slots, emit, expose }) {
const menuVisibleChildren = inject("menuVisible");
const togal = () => {
menuVisibleChildren.value = !menuVisibleChildren.value;
};
return {
togal,
menuVisibleChildren,
attrs, // Attribute (非响应式对象,等同于 attrs),有状态,会随组件本身的更新而更新
slots,
emit, // 触发事件 (方法,等同于 emit)
expose, // 暴露公共 property (函数)
};
},
methods: {},
});
</script>
<style lang="scss" scoped></style>