🏠個人主頁:Yui_
🍑操作環境:vscode\node.js
🚀所屬專欄:Vue3
文章目錄
- 1. 計算屬性
- 1.1 computed函數
- 1.2 計算屬性VS普通函數
- 1.3 計算屬性的完整寫法
- 2. 監聽器
- 3.總結
1. 計算屬性
計算屬性(computed)是 Vue 中用于根據已有數據動態計算新數據的屬性。它的特點是基于依賴進行緩存,只有相關依賴發生變化時才會重新計算,適合處理復雜邏輯或需要復用的表達式。
1.1 computed函數
語法:
const 新數據 = computed(() => {
return 計算結果
})
<script setup>
import { ref, computed } from 'vue'const count = ref(1)
const double = computed(() => count.value * 2)
</script><template><div>{{ double }}</div>
</template>
只要count的數字變化,double的數字就會自動變化
演示:
<script setup>
import { ref, computed } from 'vue'const cart = ref([{ id: 1, name: '蘋果', price: 3, count: 2, checked: true },{ id: 2, name: '香蕉', price: 2, count: 1, checked: false },{ id: 3, name: '橙子', price: 4, count: 3, checked: true }
])// 計算已選商品總價
const totalPrice = computed(() =>cart.value.filter(item => item.checked).reduce((sum, item) => sum + item.price * item.count, 0)
)// 計算已選商品數量
const selectedCount = computed(() =>cart.value.filter(item => item.checked).length
)// 增減商品數量
function changeCount(item, delta) {item.count += deltaif (item.count < 1) item.count = 1
}
</script><template><h2>購物車</h2><ul><li v-for="item in cart" :key="item.id"><input type="checkbox" v-model="item.checked" />{{ item.name }} - 單價:{{ item.price }} 元<button @click="changeCount(item, -1)">-</button>{{ item.count }}<button @click="changeCount(item, 1)">+</button></li></ul><p>已選商品數量:{{ selectedCount }}</p><p>總價:{{ totalPrice }} 元</p>
</template>
注意:
- 計算屬性必須又返回值
1.2 計算屬性VS普通函數
貌似普通的函數也能做像計算屬性哪些功能吧。
計算屬性(computed)和普通函數(methods)在 Vue 中都可以實現基于數據的動態計算,但它們有以下區別:
- 計算屬性(computed)
- 有緩存:依賴的數據不變時,計算屬性不會重新執行,直接返回上次的結果。
- 適合依賴響應式數據的復雜邏輯,如總價、過濾、格式化等。
- 普通函數(methods)
- 無緩存:每次調用都會重新執行函數體。
- 適合處理事件、無狀態邏輯或不依賴響應式數據的場景。
1.3 計算屬性的完整寫法
計算屬性的完整寫法可以使用對象形式,包含 get
(和可選的 set
)方法。
示例:
<script setup>
import { ref, computed } from 'vue'const count = ref(1)// 只讀計算屬性
const double = computed(() => count.value * 2)// 可讀可寫計算屬性
const doublePlus = computed({get() {return count.value * 2},set(val) {count.value = val / 2}
})
</script><template><div><p>count: {{ count }}</p><p>double: {{ double }}</p><input v-model="doublePlus"></div>
</template>
2. 監聽器
偵聽器(watcher)是 Vue 中用于監聽響應式數據變化并執行副作用操作的工具。常用于異步請求、復雜邏輯處理或需要在數據變化時執行特定操作的場景。
語法:
<script setup>
import { ref, watch } from 'vue'const count = ref(0)watch(count, (newVal, oldVal) => {console.log(`count 從 ${oldVal} 變為 ${newVal}`)
})
</script>
演示:
<template>
<div><input type="text" v-model="keyword">
</div>
</template><script setup>import {ref,watch} from "vue"const keyword = ref('')watch(keyword,(newVal,oldVal)=>{console.log(`新值為${newVal},舊值為${oldVal}`)})
</script><style scoped></style>
watch的作用就是監視響應式數據的變化,當數據變了,針對性的DOM操作或異步操作
3.總結
計算屬性(computed)用于根據已有數據動態計算新值,具有緩存特性,適合模板展示和數據派生;偵聽器(watch)用于監聽響應式數據的變化并執行副作用操作,如異步請求或復雜邏輯,適合處理數據變化帶來的過程和操作。兩者結合使用,可以讓 Vue 應用既高效又靈活。
往期文章:
Vue3入門-必會前置知識-CSDN博客
Vue3入門-聲明式渲染+數據響應式-CSDN博客
Vue3入門-指令-CSDN博客
Vue3入門-指令補充-CSDN博客
Vue3入門-組件及組件化-CSDN博客