跳轉到內容

響應式基礎

API 選項

本頁和指南中後續的許多章節包含針對 Options API 和組合式 API 的不同內容。您的當前偏好是 Options API組合式 API。您可以透過左側側邊欄頂部的“API 偏好”開關在 API 風格之間切換。

宣告響應式狀態

使用 Options API,我們透過 data 選項宣告元件的響應式狀態。選項值應該是一個返回物件的函式。Vue 在建立新的元件例項時將呼叫該函式,並將其返回的物件包裝在其響應性系統中。該物件的任何頂級屬性都將代理到元件例項(在方法和生命週期鉤子中是 this)。

js
export default {
  data() {
    return {
      count: 1
    }
  },

  // `mounted` is a lifecycle hook which we will explain later
  mounted() {
    // `this` refers to the component instance.
    console.log(this.count) // => 1

    // data can be mutated as well
    this.count = 2
  }
}

在遊樂場嘗試它

這些例項屬性僅在例項首次建立時新增,因此您需要確保它們都包含在 data 函式返回的物件中。必要時,使用 nullundefined 或其他佔位符值作為尚未提供所需值的屬性。

可以直接向 this 新增新屬性,而不將其包含在 data 中。然而,以這種方式新增的屬性將無法觸發響應式更新。

Vue 在透過元件例項公開其自己的內建 API 時使用 $ 字首。它還保留了 _ 字首以用於內部屬性。您應避免為頂級 data 屬性使用以這兩個字元之一開頭的名稱。

響應式代理與原始

在 Vue 3 中,透過利用 JavaScript Proxies 來使資料響應式。來自 Vue 2 的使用者應該注意以下邊緣情況

js
export default {
  data() {
    return {
      someObject: {}
    }
  },
  mounted() {
    const newObject = {}
    this.someObject = newObject

    console.log(newObject === this.someObject) // false
  }
}

在分配後訪問 this.someObject,該值是原始 newObject 的響應式代理。與 Vue 2 不同,原始的 newObject 仍然保持原樣,並且不會被使其響應式:請確保始終將響應式狀態作為 this 的屬性訪問。

宣告響應式狀態

ref()

在組合式 API 中,宣告響應式狀態的建議方法是使用 ref() 函式。

js
import { ref } from 'vue'

const count = ref(0)

ref() 接收一個引數,並返回一個具有 .value 屬性的包裝在 ref 物件中的值。

js
const count = ref(0)

console.log(count) // { value: 0 }
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

另請參閱: 引用型別

要訪問元件模板中的引用,請從元件的 setup() 函式中宣告並返回它們。

js
import { ref } from 'vue'

export default {
  // `setup` is a special hook dedicated for the Composition API.
  setup() {
    const count = ref(0)

    // expose the ref to the template
    return {
      count
    }
  }
}
template
<div>{{ count }}</div>

請注意,在使用模板中的引用時,我們 不需要 新增 .value。為了方便,當在模板中使用時,引用將自動解包(有一些 注意事項)。

您還可以直接在事件處理程式中更改引用。

template
<button @click="count++">
  {{ count }}
</button>

對於更復雜的邏輯,我們可以宣告在相同作用域中更改引用的函式,並將它們作為方法與狀態一起公開。

js
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    function increment() {
      // .value is needed in JavaScript
      count.value++
    }

    // don't forget to expose the function as well.
    return {
      count,
      increment
    }
  }
}

公開的方法然後可以用作事件處理程式。

template
<button @click="increment">
  {{ count }}
</button>

以下示例在 Codepen 上即時演示,不使用任何構建工具。

<script setup>

透過 setup() 手動公開狀態和方法可能會很冗長。幸運的是,在使用 單檔案元件 (SFCs) 時可以避免這種情況。我們可以透過使用 <script setup> 來簡化使用。

vue
<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">
    {{ count }}
  </button>
</template>

在遊樂場嘗試它

在 `