JavaScript/vue.js/Provide Inject:修订间差异
来自康健生活
创建页面,内容为“== 标题文本 == == ref == 配置文件 {{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> import { type InjectionKey, type Ref } from 'vue' export const DEFAULT_PARAMS = 1 export const valueKey = Symbol('value_symbol_string') as InjectionKey<Ref<number>> </syntaxhighlight>}} 父组件,上级组件 <syntaxhighlight lang="html5"> <script lang="ts" setup> import { provide, ref } from 'vue' import { DEFAULT_PARAMS, valueKey } from './config' ... co…” |
|||
| 第33行: | 第33行: | ||
配置文件 | 配置文件 | ||
{{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> | {{hc|head=conf.ts|output=<syntaxhighlight lang="javascript"> | ||
import { type InjectionKey, type | import { type InjectionKey, type Reactive } from 'vue' | ||
export const | export interface IFRect { | ||
export const | x: number | ||
y: number | |||
width: number | |||
height: number | |||
} | |||
export const DEFAULT_RECT = { | |||
x: 0, | |||
y: 0, | |||
width: 0, | |||
height: 0, | |||
} | |||
export const rectKey: InjectionKey<Reactive<IFRect>> = Symbol('rect') | |||
</syntaxhighlight>}} | </syntaxhighlight>}} | ||
| 第42行: | 第53行: | ||
<syntaxhighlight lang="html5"> | <syntaxhighlight lang="html5"> | ||
<script lang="ts" setup> | <script lang="ts" setup> | ||
import { provide, | import { provide, reactive, type PropType } from 'vue' | ||
import { | import { DEFAULT_RECT, rectKey, type IFRect } from './config' | ||
... | ... | ||
const | const props = defineProps({ | ||
provide( | rect: { | ||
type: Object as PropType<IFRect>, | |||
default: () => DEFAULT_RECT as IFRect, | |||
}, | |||
}) | |||
const rectReactive = reactive(props.rect || DEFAULT_RECT) | |||
provide(rectKey, rectReactive) | |||
</script> | </script> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| 第54行: | 第71行: | ||
<syntaxhighlight lang="html5"> | <syntaxhighlight lang="html5"> | ||
<script lang="ts" setup> | <script lang="ts" setup> | ||
import { inject, | import { inject, reactive } from 'vue' | ||
import { | import { DEFAULT_RECT, rectKey} from './config' | ||
... | ... | ||
const | const rect = inject(rectKey, reactive(DEFAULT_RECT)) | ||
</syntaxhighlight> | </syntaxhighlight> | ||