前端(vue)入門(mén)到精通課程:進(jìn)入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點(diǎn)擊使用
一、計(jì)算屬性computed
1.1.什么是計(jì)算屬性computed
⭐⭐
computed 是基于它的依賴緩存,只有在它的相關(guān)依賴發(fā)生改變時(shí)才會(huì)進(jìn)行更新。官方文檔是這樣說(shuō)的:對(duì)于任何包含響應(yīng)式數(shù)據(jù)的復(fù)雜邏輯,你都應(yīng)該使用計(jì)算屬性。?(學(xué)習(xí)視頻分享:vue視頻教程)
1.2.復(fù)雜數(shù)據(jù)的處理-computed
⭐⭐
拼接字符串、分?jǐn)?shù)是否及格、message記錄一段文字,這里是用computed實(shí)現(xiàn)的
<div id="app"> <!-- 插值語(yǔ)法表達(dá)式直接進(jìn)行拼接 --> <!-- 1.拼接姓名 --> <h2>{{fullname}}</h2> <!-- 2.顯示分?jǐn)?shù)及格或不及格 --> <h2>{{scorelevel}}</h2> <!-- 3.反轉(zhuǎn)單詞 --> <!-- reverse針對(duì)于數(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插值語(yǔ)法、methods也是可以完成的,但是對(duì)于復(fù)雜數(shù)據(jù)的處理,我們往往采用computed,寫(xiě)法更清晰,且計(jì)算屬性是有緩存的
1.3.計(jì)算屬性的緩存
⭐⭐
- 會(huì)基于它們的依賴關(guān)系進(jìn)行緩存;
- 在數(shù)據(jù)不發(fā)生變化時(shí),計(jì)算屬性是不需要重新計(jì)算的;
- 但是如果依賴的數(shù)據(jù)發(fā)生變化,在使用時(shí),計(jì)算屬性依然會(huì)重新進(jìn)行計(jì)算;
&tinsp;
所以這也是我們?cè)趶?fù)雜數(shù)據(jù)處理時(shí)更傾向于computed
-
在使用相同次數(shù)的fullName時(shí),methods執(zhí)行三次,computed執(zhí)行一次,這正是由于computed計(jì)算屬性會(huì)被緩存
1.4.計(jì)算屬性computed的setter和getter
⭐⭐
大多數(shù)情況下,計(jì)算屬性只需要一個(gè)getter方法,那么此時(shí)computed屬性屬性值為函數(shù)
如果想要設(shè)置計(jì)算屬性的值,我們可以給計(jì)算屬性設(shè)置一個(gè)setter方法
computed: { // 語(yǔ)法糖 fullname() { return this.firstname + " " + this.lastname; }, // 完整寫(xiě)法 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)視頻教程推薦:vuejs入門(mén)教程、web前端入門(mén)】