Vue computed計算屬性詳細(xì)講解
一、計算屬性computed
1.1.什么是計算屬性computed
??
computed 是基于它的依賴緩存,只有在它的相關(guān)依賴發(fā)生改變時才會進(jìn)行更新。官方文檔是這樣說的:對于任何包含響應(yīng)式數(shù)據(jù)的復(fù)雜邏輯,你都應(yīng)該使用計算屬性
1.2.復(fù)雜數(shù)據(jù)的處理-computed
??
拼接字符串、分?jǐn)?shù)是否及格、message記錄一段文字,這里是用computed實現(xiàn)的
<div id="app"> <!-- 插值語法表達(dá)式直接進(jìn)行拼接 --> <!-- 1.拼接姓名 --> <h2>{{fullname}}</h2> <!-- 2.顯示分?jǐn)?shù)及格或不及格 --> <h2>{{scorelevel}}</h2> <!-- 3.反轉(zhuǎn)單詞 --> <!-- reverse針對于數(shù)組,先用split轉(zhuǎn)為數(shù)組,在用reverse --> <h2>{{reversetext}}</h2> </div> <script src="../lib/vue.js"></script> <script> const app = Vue.createApp({ data() { return { // name firstName: "kk", lastName: "cc", // score score: 99, // 文本中單詞反轉(zhuǎn) message: "I love stydy Vue3", }; }, computed: { fullname() { return this.firstName + " " + this.lastName; }, scorelevel() { return this.score >= 60 ? "及格" : "不及格"; }, reversetext() { return this.message.split(" ").reverse().join(" "); }, }, }); app.mount("#app");
當(dāng)然我們用Mustache插值語法、methods也是可以完成的,但是對于復(fù)雜數(shù)據(jù)的處理,我們往往采用computed,寫法更清晰,且計算屬性是有緩存的
1.3.計算屬性的緩存
??
- 會基于它們的依賴關(guān)系進(jìn)行緩存;
- 在數(shù)據(jù)不發(fā)生變化時,計算屬性是不需要重新計算的;
- 但是如果依賴的數(shù)據(jù)發(fā)生變化,在使用時,計算屬性依然會重新進(jìn)行計算;
&tinsp;
所以這也是我們在復(fù)雜數(shù)據(jù)處理時更傾向于computed
在使用相同次數(shù)的fullName時,methods執(zhí)行三次,computed執(zhí)行一次,這正是由于computed計算屬性會被緩存
1.4.計算屬性computed的setter和getter
??
大多數(shù)情況下,計算屬性只需要一個getter方法,那么此時computed屬性屬性值為函數(shù)
如果想要設(shè)置計算屬性的值,我們可以給計算屬性設(shè)置一個setter方法
computed: { // 語法糖 fullname() { return this.firstname + " " + this.lastname; }, // 完整寫法 fullname: { get: function () { return this.firstname + " " + this.lastname; }, set: function (value) { const names = value.split(" "); this.firstname = names[0]; this.lastname = names[1]; }, },
到此這篇關(guān)于Vue computed計算屬性詳細(xì)講解的文章就介紹到這了,更多相關(guān)Vue computed內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-router 源碼之實現(xiàn)一個簡單的 vue-router
這篇文章主要介紹了vue-router 源碼之實現(xiàn)一個簡單的 vue-router,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07Vuejs 組件——props數(shù)據(jù)傳遞的實例代碼
本篇文章主要介紹了Vuejs 組件——props數(shù)據(jù)傳遞的實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03vue中用js如何實現(xiàn)循環(huán)可編輯表格
這篇文章主要介紹了vue中用js如何實現(xiàn)循環(huán)可編輯表格,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09