通过从祖先提供者中定位属性来声明要注入当前组件的属性。
类型
interface ComponentOptions {
inject?: ArrayInjectOptions | ObjectInjectOptions
}
type ArrayInjectOptions = string[]
type ObjectInjectOptions = {
[key: string | symbol]:
| string
| symbol
| { from?: string | symbol; default?: any }
}
细节
inject
选项应该是:
- 字符串数组,或
- 一个对象,其中键是本地绑定名称,值是:
- 在可用注入中搜索的键(字符串或符号),或
- 一个对象,其中:
from
属性是在可用注入中搜索的键(字符串或符号),并且default
属性用作备用值。类似于 props 的默认值,对象类型需要一个工厂函数来避免多个组件实例之间的值共享。
如果既没有提供匹配的属性也没有提供默认值,则注入的属性将为 undefined
。
请注意,注入的绑定不是反应式的。这是故意的。但是,如果注入的值是响应式对象,则该对象上的属性确实保持响应式。有关详细信息,请参阅Working with Reactivity。
示例
基本用法:
export default {
inject: ['foo'],
created() {
console.log(this.foo)
}
}
使用注入的值作为道具的默认值:
const Child = {
inject: ['foo'],
props: {
bar: {
default() {
return this.foo
}
}
}
}
使用注入值作为数据输入:
const Child = {
inject: ['foo'],
data() {
return {
bar: this.foo
}
}
}
注入可以是可选的,具有默认值:
const Child = {
inject: {
foo: { default: 'foo' }
}
}
如果需要从具有不同名称的属性注入,请使用from
来表示源属性:
const Child = {
inject: {
foo: {
from: 'bar',
default: 'foo'
}
}
}
与 prop 默认值类似,您需要对非原始值使用工厂函数:
const Child = {
inject: {
foo: {
from: 'bar',
default: () => [1, 2, 3]
}
}
}
相关用法
- Vue.js inject()用法及代码示例
- Vue.js inheritAttrs用法及代码示例
- Vue.js useSSRContext()用法及代码示例
- Vue.js app.directive()用法及代码示例
- Vue.js mergeProps()用法及代码示例
- Vue.js app.config.warnHandler用法及代码示例
- Vue.js pipeToWebWritable()用法及代码示例
- Vue.js app.use()用法及代码示例
- Vue.js v-pre用法及代码示例
- Vue.js h()用法及代码示例
- Vue.js serverPrefetch用法及代码示例
- Vue.js customRef()用法及代码示例
- Vue.js <Transition>用法及代码示例
- Vue.js mixins用法及代码示例
- Vue.js ComponentCustomProps用法及代码示例
- Vue.js reactive()用法及代码示例
- Vue.js ComponentCustomProperties用法及代码示例
- Vue.js app.mount()用法及代码示例
- Vue.js <component>用法及代码示例
- Vue.js createRenderer()用法及代码示例
- Vue.js onMounted()用法及代码示例
- Vue.js createApp()用法及代码示例
- Vue.js app.config.errorHandler用法及代码示例
- Vue.js v-on用法及代码示例
- Vue.js components用法及代码示例
注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 inject。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。