跳轉到內容

選項:狀態

data

一個返回元件例項初始響應式狀態的函式。

  • 型別

    ts
    interface ComponentOptions {
      data?(
        this: ComponentPublicInstance,
        vm: ComponentPublicInstance
      ): object
    }
  • 詳情

    該函式預期返回一個普通的 JavaScript 物件,Vue 將將其變為響應式。例項建立後,可以訪問響應式資料物件為 this.$data。元件例項還代理了資料物件上找到的所有屬性,因此 this.a 等同於 this.$data.a

    所有頂級資料屬性都必須包含在返回的資料物件中。向 this.$data 新增新屬性是可能的,但不推薦。如果屬性的期望值尚未可用,則應包含空值,例如 undefinednull,以確保 Vue 知道屬性存在。

    _$ 開頭的屬性將不會在元件例項上代理,因為它們可能與 Vue 的內部屬性和 API 方法衝突。您必須透過 this.$data._property 來訪問它們。

    不推薦返回具有自身狀態行為的物件,如瀏覽器 API 物件和原型屬性。返回的物件應理想地是一個僅表示元件狀態的普通物件。

  • 示例

    js
    export default {
      data() {
        return { a: 1 }
      },
      created() {
        console.log(this.a) // 1
        console.log(this.$data) // { a: 1 }
      }
    }

    注意,如果使用具有 data 屬性的箭頭函式,則 this 不會是元件的例項,但您仍然可以透過函式的第一個引數訪問例項

    js
    data: (vm) => ({ a: vm.myProp })
  • 另請參閱 深入響應式原理

props

宣告元件的 props。

  • 型別

    ts
    interface ComponentOptions {
      props?: ArrayPropsOptions | ObjectPropsOptions
    }
    
    type ArrayPropsOptions = string[]
    
    type ObjectPropsOptions = { [key: string]: Prop }
    
    type Prop<T = any> = PropOptions<T> | PropType<T> | null
    
    interface PropOptions<T> {
      type?: PropType<T>
      required?: boolean
      default?: T | ((rawProps: object) => T)
      validator?: (value: unknown, rawProps: object) => boolean
    }
    
    type PropType<T> = { new (): T } | { new (): T }[]

    型別簡化以提高可讀性。

  • 詳情

    在 Vue 中,所有元件 props 都需要顯式宣告。元件 props 可以以兩種形式宣告

    • 使用字串陣列簡單形式
    • 使用物件完整形式,其中每個屬性鍵是 prop 名稱,值是 prop 型別(建構函式)或高階選項。

    使用基於物件的語法,每個 prop 可以進一步定義以下選項

    • type:可以是以下原生建構函式之一:StringNumberBooleanArrayObjectDateFunctionSymbol、任何自定義建構函式或這些的陣列。在開發模式下,Vue 將檢查 prop 的值是否與宣告的型別匹配,如果不匹配,將丟擲警告。有關詳細資訊,請參閱 Prop 驗證

      請注意,具有 Boolean 型別的 prop 會影響其在開發和生產環境中的值轉換行為。有關更多詳細資訊,請參閱 布林轉換

    • default:指定當父元件未傳遞或具有 undefined 值時 prop 的預設值。物件或陣列預設值必須透過工廠函式返回。工廠函式還將接收原始 prop 物件作為引數。

    • required:定義 prop 是否必需。在非生產環境中,如果此值為真且未傳遞 prop,將丟擲控制檯警告。

    • validator:自定義驗證函式,它只接受 prop 值作為引數。在開發模式中,如果此函式返回一個假值(即驗證失敗),將丟擲控制檯警告。

  • 示例

    簡單宣告

    js
    export default {
      props: ['size', 'myMessage']
    }

    具有驗證的物件宣告

    js
    export default {
      props: {
        // type check
        height: Number,
        // type check plus other validations
        age: {
          type: Number,
          default: 0,
          required: true,
          validator: (value) => {
            return value >= 0
          }
        }
      }
    }
  • 另請參閱

computed

宣告要暴露在元件例項上的計算屬性。

  • 型別

    ts
    interface ComponentOptions {
      computed?: {
        [key: string]: ComputedGetter<any> | WritableComputedOptions<any>
      }
    }
    
    type ComputedGetter<T> = (
      this: ComponentPublicInstance,
      vm: ComponentPublicInstance
    ) => T
    
    type ComputedSetter<T> = (
      this: ComponentPublicInstance,
      value: T
    ) => void
    
    type WritableComputedOptions<T> = {
      get: ComputedGetter<T>
      set: ComputedSetter<T>
    }
  • 詳情

    此選項接受一個物件,其中鍵是計算屬性的名稱,值是計算獲取器或具有 getset 方法的物件(對於可寫計算屬性)。

    所有獲取器和設定器都自動將它們的 this 上下文繫結到元件例項。

    請注意,如果您使用箭頭函式與計算屬性一起使用,則 this 不會指向元件例項,但您仍然可以透過函式的第一個引數訪問例項。

    js
    export default {
      computed: {
        aDouble: (vm) => vm.a * 2
      }
    }
  • 示例

    js
    export default {
      data() {
        return { a: 1 }
      },
      computed: {
        // readonly
        aDouble() {
          return this.a * 2
        },
        // writable
        aPlus: {
          get() {
            return this.a + 1
          },
          set(v) {
            this.a = v - 1
          }
        }
      },
      created() {
        console.log(this.aDouble) // => 2
        console.log(this.aPlus) // => 2
    
        this.aPlus = 3
        console.log(this.a) // => 2
        console.log(this.aDouble) // => 4
      }
    }
  • 另請參閱

methods

宣告要混合到元件例項中的方法。

  • 型別

    ts
    interface ComponentOptions {
      methods?: {
        [key: string]: (this: ComponentPublicInstance, ...args: any[]) => any
      }
    }
  • 詳情

    宣告的可以在元件例項上直接訪問的方法,或在模板表示式中使用。所有方法都自動將它們的 this 上下文繫結到元件例項,即使在傳遞時也是如此。

    在宣告方法時避免使用箭頭函式,因為它們無法透過 this 訪問元件例項。

  • 示例

    js
    export default {
      data() {
        return { a: 1 }
      },
      methods: {
        plus() {
          this.a++
        }
      },
      created() {
        this.plus()
        console.log(this.a) // => 2
      }
    }
  • 另請參閱 事件處理

watch

宣告在資料更改時呼叫的監視回撥。

  • 型別

    ts
    interface ComponentOptions {
      watch?: {
        [key: string]: WatchOptionItem | WatchOptionItem[]
      }
    }
    
    type WatchOptionItem = string | WatchCallback | ObjectWatchOptionItem
    
    type WatchCallback<T> = (
      value: T,
      oldValue: T,
      onCleanup: (cleanupFn: () => void) => void
    ) => void
    
    type ObjectWatchOptionItem = {
      handler: WatchCallback | string
      immediate?: boolean // default: false
      deep?: boolean // default: false
      flush?: 'pre' | 'post' | 'sync' // default: 'pre'
      onTrack?: (event: DebuggerEvent) => void
      onTrigger?: (event: DebuggerEvent) => void
    }

    型別簡化以提高可讀性。

  • 詳情

    watch 選項期望一個物件,其中鍵是要監視的響應式元件例項屬性(例如透過 datacomputed 宣告的屬性)——值是相應的回撥。回撥接收監視源的舊值和新值。

    除了根級屬性之外,鍵還可以是一個簡單的點分隔路徑,例如 a.b.c。請注意,此用法不支援複雜表示式——只支援點分隔路徑。如果您需要監視複雜資料來源,請使用命令式 $watch() API。

    值還可以是方法名(透過 methods 宣告)的字串,或包含附加選項的物件。當使用物件語法時,回撥應在 handler 欄位下宣告。附加選項包括

    • immediate:在建立監視器時立即觸發回撥。第一次呼叫時舊值將是 undefined
    • deep:如果源是物件或陣列,強制深度遍歷,以便在深度突變時觸發回撥。請參閱 深度監視器
    • flush:調整回撥的重新整理時間。請參閱 回撥重新整理時間watchEffect()
    • onTrack / onTrigger:除錯監視器的依賴項。請參閱 監視器除錯

    在宣告監視回撥時避免使用箭頭函式,因為它們將無法透過 this 訪問元件例項。

  • 示例

    js
    export default {
      data() {
        return {
          a: 1,
          b: 2,
          c: {
            d: 4
          },
          e: 5,
          f: 6
        }
      },
      watch: {
        // watching top-level property
        a(val, oldVal) {
          console.log(`new: ${val}, old: ${oldVal}`)
        },
        // string method name
        b: 'someMethod',
        // the callback will be called whenever any of the watched object properties change regardless of their nested depth
        c: {
          handler(val, oldVal) {
            console.log('c changed')
          },
          deep: true
        },
        // watching a single nested property:
        'c.d': function (val, oldVal) {
          // do something
        },
        // the callback will be called immediately after the start of the observation
        e: {
          handler(val, oldVal) {
            console.log('e changed')
          },
          immediate: true
        },
        // you can pass array of callbacks, they will be called one-by-one
        f: [
          'handle1',
          function handle2(val, oldVal) {
            console.log('handle2 triggered')
          },
          {
            handler: function handle3(val, oldVal) {
              console.log('handle3 triggered')
            }
            /* ... */
          }
        ]
      },
      methods: {
        someMethod() {
          console.log('b changed')
        },
        handle1() {
          console.log('handle 1 triggered')
        }
      },
      created() {
        this.a = 3 // => new: 3, old: 1
      }
    }
  • 另請參閱 監視器

emit

宣告元件發出的自定義事件。

  • 型別

    ts
    interface ComponentOptions {
      emits?: ArrayEmitsOptions | ObjectEmitsOptions
    }
    
    type ArrayEmitsOptions = string[]
    
    type ObjectEmitsOptions = { [key: string]: EmitValidator | null }
    
    type EmitValidator = (...args: unknown[]) => boolean
  • 詳情

    發出的事件可以以兩種形式宣告

    • 使用字串陣列簡單形式
    • 使用物件的全形式,其中每個屬性鍵是事件名稱,值是 null 或驗證函式。

    驗證函式將接收傳遞給元件 $emit 呼叫的額外引數。例如,如果呼叫 this.$emit('foo', 1),則 foo 的相應驗證函式將接收引數 1。驗證函式應返回一個布林值以指示事件引數是否有效。

    請注意,emits 選項會影響哪些事件監聽器被視為元件事件監聽器,而不是原生 DOM 事件監聽器。宣告的監聽器將從元件的 $attrs 物件中刪除,因此它們不會傳遞到元件的根元素。有關更多詳細資訊,請參閱 穿透屬性

  • 示例

    陣列語法

    js
    export default {
      emits: ['check'],
      created() {
        this.$emit('check')
      }
    }

    物件語法

    js
    export default {
      emits: {
        // no validation
        click: null,
    
        // with validation
        submit: (payload) => {
          if (payload.email && payload.password) {
            return true
          } else {
            console.warn(`Invalid submit event payload!`)
            return false
          }
        }
      }
    }
  • 另請參閱

expose

當元件例項透過模板引用由父元件訪問時,宣告公開的公共屬性。

  • 型別

    ts
    interface ComponentOptions {
      expose?: string[]
    }
  • 詳情

    預設情況下,當透過 $parent$root 或模板引用訪問元件例項時,元件例項會公開所有例項屬性。這可能是不希望的,因為元件很可能有內部狀態或方法,應該保持私有以避免緊密耦合。

    expose 選項期望一個屬性名稱字串列表。當使用 expose 時,只有明確列出的屬性將在元件的公共例項上公開。

    expose 隻影響使用者定義的屬性 - 它不會過濾掉內建元件例項屬性。

  • 示例

    js
    export default {
      // only `publicMethod` will be available on the public instance
      expose: ['publicMethod'],
      methods: {
        publicMethod() {
          // ...
        },
        privateMethod() {
          // ...
        }
      }
    }
選項:狀態已載入