Skip to content

分类:Provide/Inject

作者:JiangHong
链接:https://juejin.cn/post/7249624871722221623
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

@niu-tools/vue3
createContext
light
<script setup lang="ts">
import { ref } from 'vue';
import { ThemeContext } from './ThemeContext';
import Page from './demo2.vue';

const theme = ref('light');
</script>

<template>
  <ThemeContext.Provider :value="theme">
    <Page></Page>
  </ThemeContext.Provider>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ThemeContext } from './ThemeContext';
import Page from './demo2.vue';

const theme = ref('light');
</script>

<template>
  <ThemeContext.Provider :value="theme">
    <Page></Page>
  </ThemeContext.Provider>
</template>

源码

查看源码
createContextComponent/createContextComponent.ts源码
ts
import { defineComponent, provide, computed, inject, type PropType, type ComputedRef } from 'vue';

export function createContextComponent<T>(defaultValue: T) {
    const KEY = Symbol('CREATE_CONTEXT_KEY');
    const Provider = defineComponent({
        props: {
            value: {
                type: [Object, Number, String, Boolean, null, undefined, Function] as PropType<T>,
                required: true,
            },
        },
        setup(props, ctx) {
            provide(
                KEY,
                computed(() => props.value || defaultValue),
            );
            return () => ctx.slots.default?.();
        },
    });

    const useContext = () => inject<ComputedRef<T>>(KEY) || computed(() => defaultValue);

    const Consumer = defineComponent({
        setup(props, ctx) {
            const value = useContext();
            return () => ctx.slots.default?.(value.value);
        },
    });

    return {
        Provider,
        Consumer,
        useContext
    };
}
import { defineComponent, provide, computed, inject, type PropType, type ComputedRef } from 'vue';

export function createContextComponent<T>(defaultValue: T) {
    const KEY = Symbol('CREATE_CONTEXT_KEY');
    const Provider = defineComponent({
        props: {
            value: {
                type: [Object, Number, String, Boolean, null, undefined, Function] as PropType<T>,
                required: true,
            },
        },
        setup(props, ctx) {
            provide(
                KEY,
                computed(() => props.value || defaultValue),
            );
            return () => ctx.slots.default?.();
        },
    });

    const useContext = () => inject<ComputedRef<T>>(KEY) || computed(() => defaultValue);

    const Consumer = defineComponent({
        setup(props, ctx) {
            const value = useContext();
            return () => ctx.slots.default?.(value.value);
        },
    });

    return {
        Provider,
        Consumer,
        useContext
    };
}
createContextComponent/index.ts源码
ts
export * from "./createContextComponent"
export * from "./createContextComponent"

Released under the MIT License.