JavaScript/vue.js/Provide Inject:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 标题文本 == == 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…”
 
Kangkk​(留言 | 贡献)
第33行: 第33行:
配置文件
配置文件
{{hc|head=conf.ts|output=<syntaxhighlight lang="javascript">
{{hc|head=conf.ts|output=<syntaxhighlight lang="javascript">
import { type InjectionKey, type Ref } from 'vue'
import { type InjectionKey, type Reactive } from 'vue'
export const DEFAULT_PARAMS = 1
export interface IFRect {
export const valueKey = Symbol('value_symbol_string') as InjectionKey<Ref<number>>
  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, ref } from 'vue'
import { provide, reactive, type PropType } from 'vue'
import { DEFAULT_PARAMS, valueKey } from './config'
import { DEFAULT_RECT, rectKey, type IFRect } from './config'
...
...
const valueRef = ref(props.params || DEFAULT_PARAMS)
const props = defineProps({
provide(valueKey, valueRef)
  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, ref } from 'vue'
import { inject, reactive } from 'vue'
import { DEFAULT_PARAMS, valueKey } from './config'
import { DEFAULT_RECT, rectKey} from './config'
...
...
const value= inject(valueKey, ref(DEFAULT_PARAMS))
const rect = inject(rectKey, reactive(DEFAULT_RECT))
</syntaxhighlight>
</syntaxhighlight>