Skip to content

useContext

useContext 类似于 React 上的useContext可让你从在 vue 组件中读取和订阅上下文。

one.vue

count:0

two.vue

three.vue

count:0
实现代码
vue
<template>
  <div class="container-one">
    <h1>one.vue</h1>
    <div>
      <Tag color="#108ee9">count:{{ count }}</Tag>
      <Button type="primary" @click="plusOne">count plus one</Button>
    </div>
    <two />
  </div>
</template>
<script setup>
import { Tag, Button } from '@aplus-frontend/antdv';
import { createAppProviderContext } from '../useCountContext.ts';
import two from './two.vue';
import { ref } from 'vue';
const count = ref(0);
const plusOne = () => {
  count.value++;
};
createAppProviderContext(count);
</script>
<style lang="less">
.container-one {
  padding: 10px;
  border: 1px solid #ccc;
  color: #000;
}
</style>
vue
<template>
  <div class="container-two">
    <h1>two.vue</h1>
    <three />
  </div>
</template>
<script setup>
import three from './three.vue';
</script>
<style lang="less">
.container-two {
  padding: 10px;
  border: 1px solid #ccc;
  color: #000;
  margin: 10px;
}
</style>
vue
<template>
  <div class="container-three">
    <h1>three.vue</h1>
    <div>
      <Tag color="#108ee9">count:{{ count }}</Tag>
    </div>
  </div>
</template>
<script setup>
import { Tag } from '@aplus-frontend/antdv';
import { useCountProviderContext } from '../useCountContext.ts';
const count = useCountProviderContext();
</script>
<style lang="less">
.container-three {
  padding: 10px;
  border: 1px solid #ccc;
  color: #000;
  margin: 10px;
}
</style>
ts
import { InjectionKey, Ref } from 'vue';
import { createContext, useContext } from '@aplus-frontend/hooks';
export interface countProviderContextProps {
  count: Ref<number>;
}
const key: InjectionKey<countProviderContextProps> = Symbol();

export function createAppProviderContext(context: countProviderContextProps) {
  return createContext<countProviderContextProps>(context, key);
}

export function useCountProviderContext() {
  return useContext<countProviderContextProps>(key);
}

Type Declarations

jsx

function createContext<T>(context: any, key?: InjectionKey<T>, options?: CreateContextOptions): {
    state: any;
}

function useContext<T>(key: InjectionKey<T>, native?: boolean): T