當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js inject用法及代碼示例

通過從祖先提供者中定位屬性來聲明要注入當前組件的屬性。

類型

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]
    }
  }
}

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 inject。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。