computed
是計(jì)算屬性,它會(huì)根據(jù)響應(yīng)式數(shù)據(jù)的變化?動(dòng)計(jì)算出新的值,并緩存結(jié)果,只有在計(jì)算屬性所依賴的響應(yīng)式數(shù)據(jù)發(fā)?改變時(shí)才會(huì)重新計(jì)算。
computed
適?于需要根據(jù)響應(yīng)式數(shù)據(jù)計(jì)算得出結(jié)果的場(chǎng)景,例如根據(jù)商品的數(shù)量和單價(jià)計(jì)算商品的總價(jià),或者根據(jù)選中的過(guò)濾條件過(guò)濾出數(shù)據(jù)列表。
computed 基礎(chǔ)語(yǔ)法
<template>
<div>
<div>
性:<input v-model="firstName" type="text">
</div>
<div>
名:<input v-model="lastName" type="text">
</div>
<div>
全名:<input v-model="fullName" type="text">
</div>
<button @click="changeName">changeName</button>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
let firstName = ref('zhang')
let lastName = ref('san')
// 1.選項(xiàng)式寫法 支持一個(gè)對(duì)象傳入getter和setter自定義操作
let fullName = computed<string>({
get () {
return firstName.value + '-' + lastName.value
},
set(newVal) {
// newVal.split('-') 此時(shí)沒(méi)有 .value
console.log(newVal.split('-'));
//
[firstName.value,lastName.value] = newVal.split('-')
}
})
const changeName = () => [
fullName.value = 'xiao-hu'
]
//2.函數(shù)式寫法,只能支持一個(gè)getter函數(shù),不可以修改值
// let fullName = computed(() => firstName.value + '-' + lastName.value)
// 不可以修改,以下這個(gè)函數(shù)會(huì)報(bào)錯(cuò)
// const changeName = () => {
// fullName.value = 'xiao-hu'
// }
</script>
<style lang="scss" scoped></style>
購(gòu)物車小案例
未使用computed優(yōu)化
<template>
<div>
<input placeholder="搜索" type="text">
</div>
<div style="margin-top: 20px">
<table border width="600" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>物品名稱:</th>
<th>物品單價(jià):</th>
<th>物品數(shù)量:</th>
<th>物品總價(jià):</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in data">
<td align="center">{{ item.name }}</td>
<td align="center">{{ item.price }}</td>
<td align="center"><button @click="item.num>1 ? (item.num--, total()) : null">-</button>{{ item.num }}<button @click="item.num < 99 ? (item.num++, total()) : null">+</button></td>
<td align="center">{{ item.num * item.price }}</td>
<td align="center"><button @click="del(index)">del</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" align="right">
總價(jià):{{ $total }}
</td>
</tr>
</tfoot>
</table>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
let $total = ref<number>(0)
interface Data {
name: string,
price: number,
num: number,
}
let data = reactive<Data[]>([
{
name: '手機(jī)',
price: 100,
num: 1
},
{
name: '電腦',
price: 200,
num: 2
},
{
name: '筆記本',
price: 300,
num: 3
}
])
const total = () => {
$total.value = data.reduce((prev:number, next: Data) => {
return prev + next.num * next.price
},0)
}
total()
const del = (index:number) => {
data.splice(index, 1)
total()
}
</script>
<style lang="scss" scoped></style>
使用computed優(yōu)化
<template>
<div>
<input v-model="keyWord" placeholder="搜索" type="text">
</div>
<div style="margin-top: 20px">
<table border width="600" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>物品名稱:</th>
<th>物品單價(jià):</th>
<th>物品數(shù)量:</th>
<th>物品總價(jià):</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in searchData">
<td align="center">{{ item.name }}</td>
<td align="center">{{ item.price }}</td>
<td align="center"><button @click="item.num > 1 ? item.num-- : null">-</button>{{ item.num }}<button
@click="item.num < 99 ? item.num++ : null">+</button></td>
<td align="center">{{ item.num * item.price }}</td>
<td align="center"><button @click="del(index)">del</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" align="right">
總價(jià):{{ total }}
</td>
</tr>
</tfoot>
</table>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
let keyWord = ref<string>('')
interface Data {
name: string,
price: number,
num: number,
}
let data = reactive<Data[]>([
{
name: '手機(jī)',
price: 100,
num: 1
},
{
name: '電腦',
price: 200,
num: 2
},
{
name: '筆記本',
price: 300,
num: 3
}
])
// const total = () => {
// $total.value = data.reduce((prev:number, next: Data) => {
// return prev + next.num * next.price
// },0)
// }
const total = computed(() => {
return data.reduce((prev: number, next: Data) => {
return prev + next.num * next.price
}, 0)
})
const searchData = computed(() => {
return data.filter((item: Data) => {
return item.name.includes(keyWord.value)
})
})
// 使用 searchData 搜索后的總價(jià)有bug,不會(huì)隨 searchData 的數(shù)據(jù)改變(抽空再改啦~~)
const del = (index: number) => {
data.splice(index, 1)
}
</script>
<style lang="scss" scoped></style>
watch 和 computed 的區(qū)別:
計(jì)算屬性 computed :文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-605613.html
- 支持緩存,只有依賴數(shù)據(jù)發(fā)生改變,才會(huì)重新進(jìn)行計(jì)算
- 不支持異步,當(dāng)computed內(nèi)有異步操作時(shí)無(wú)效,無(wú)法監(jiān)聽數(shù)據(jù)的變化
- computed 屬性值會(huì)默認(rèn)走緩存,計(jì)算屬性是基于它們的響應(yīng)式依賴進(jìn)行緩存的,也就是基于data中聲明過(guò)或者父組件傳遞的props中的數(shù)據(jù)通過(guò)計(jì)算得到的值
- 如果一個(gè)屬性是由其他屬性計(jì)算而來(lái)的,這個(gè)屬性依賴其他屬性,是一個(gè)多對(duì)一或者一對(duì)一,一般用computed
- 如果computed屬性屬性值是函數(shù),那么默認(rèn)會(huì)走get方法;函數(shù)的返回值就是屬性的屬性值;在computed中的,屬性都有一個(gè)get和一個(gè)set方法,當(dāng)數(shù)據(jù)變化時(shí),調(diào)用set方法。
computed: {
// 一個(gè)計(jì)算屬性的 getter
publishedBooksMessage() {
// `this` 指向當(dāng)前組件實(shí)例
return this.author.books.length > 0 ? 'Yes' : 'No'
}
}
偵聽屬性watch:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-605613.html
- 不支持緩存,數(shù)據(jù)變,直接會(huì)觸發(fā)相應(yīng)的操作;
- watch支持異步;
- 監(jiān)聽的函數(shù)接收兩個(gè)參數(shù),第一個(gè)參數(shù)是最新的值;第二個(gè)參數(shù)是輸入之前的值;
- 當(dāng)一個(gè)屬性發(fā)生變化時(shí),需要執(zhí)行對(duì)應(yīng)的操作;一對(duì)多;
- 監(jiān)聽數(shù)據(jù)必須是data中聲明過(guò)或者父組件傳遞過(guò)來(lái)的props中的數(shù)據(jù),當(dāng)數(shù)據(jù)變化時(shí),觸發(fā)其他操作,函數(shù)有兩個(gè)參數(shù),
- immediate:組件加載立即觸發(fā)回調(diào)函數(shù)執(zhí)行,
- deep: 深度監(jiān)聽,為了發(fā)現(xiàn)對(duì)象內(nèi)部值的變化,復(fù)雜類型的數(shù)據(jù)時(shí)使用,例如數(shù)組中的對(duì)象內(nèi)容的改變,注意監(jiān)聽數(shù)組的變動(dòng)不需要這么做。
watch: {
// 每當(dāng) question 改變時(shí),這個(gè)函數(shù)就會(huì)執(zhí)行
question(newQuestion, oldQuestion) {
if (newQuestion.includes('?')) {
this.getAnswer()
}
}
},
watch: {
someObject: {
handler(newValue, oldValue) {
// 注意:在嵌套的變更中,
// 只要沒(méi)有替換對(duì)象本身,
// 那么這里的 `newValue` 和 `oldValue` 相同
},
deep: true
}
}
到了這里,關(guān)于【Vue3】computed 計(jì)算屬性的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!