前端(vue)入門到精通課程:進入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點擊使用
一、計算屬性computed
1.1.什么是計算屬性computed
⭐⭐
computed 是基于它的依賴緩存,只有在它的相關(guān)依賴發(fā)生改變時才會進行更新。官方文檔是這樣說的:對于任何包含響應(yīng)式數(shù)據(jù)的復(fù)雜邏輯,你都應(yīng)該使用計算屬性。?(學(xué)習(xí)視頻分享:vue視頻教程)
1.2.復(fù)雜數(shù)據(jù)的處理-computed
⭐⭐
拼接字符串、分數(shù)是否及格、message記錄一段文字,這里是用computed實現(xiàn)的
<div id="app"> <!-- 插值語法表達式直接進行拼接 --> <!-- 1.拼接姓名 --> <h2>{{fullname}}</h2> <!-- 2.顯示分數(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");
登錄后復(fù)制
當(dāng)然我們用Mustache插值語法、methods也是可以完成的,但是對于復(fù)雜數(shù)據(jù)的處理,我們往往采用computed,寫法更清晰,且計算屬性是有緩存的
1.3.計算屬性的緩存
⭐⭐
- 會基于它們的依賴關(guān)系進行緩存;
- 在數(shù)據(jù)不發(fā)生變化時,計算屬性是不需要重新計算的;
- 但是如果依賴的數(shù)據(jù)發(fā)生變化,在使用時,計算屬性依然會重新進行計算;
&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]; }, },
登錄后復(fù)制
【相關(guān)視頻教程推薦:vuejs入門教程、web前端入門】