響應式基礎
API 選項
本頁和指南中後續的許多章節包含針對 Options API 和組合式 API 的不同內容。您的當前偏好是 組合式 API。您可以透過左側側邊欄頂部的“API 偏好”開關在 API 風格之間切換。
宣告響應式狀態
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>
在 `