vue3中 inject provide的响应式使用

祖组件

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值