Vue.js中的計(jì)算屬性、監(jiān)視屬性與生命周期詳解
前言
本章節(jié)咱們來(lái)說(shuō)一下Vue中兩個(gè)非常重要的計(jì)算屬性、監(jiān)視屬性和生命周期,不廢話直接上干貨
計(jì)算屬性
計(jì)算屬性介紹
在模板中可以直接通過(guò)插值語(yǔ)法顯示一些data中的數(shù)據(jù),有些情況下我們需要對(duì)數(shù)據(jù)進(jìn)行轉(zhuǎn)化或者計(jì)算后顯示,我們可以使用computed選項(xiàng)來(lái)計(jì)算,這時(shí)有些小伙伴可能就會(huì)問(wèn),我直接定義函數(shù)再調(diào)用不就行了,為什么還要整一個(gè)計(jì)算屬性呢?這個(gè)問(wèn)題在下邊再做解釋,我們先來(lái)看一下計(jì)算屬性怎么用!
入門(mén)案例
需求
將人的姓和名拼接在一起
代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 原始拼接方式 -->
<p>{{fastName}} {{lastName}}</p>
<!-- 在模板語(yǔ)法中進(jìn)行計(jì)算 -->
<p>{{fastName + " " + lastName}}</p>
<!-- 調(diào)用函數(shù)計(jì)算 -->
<p v-text="fullName2()"></p>
<!-- 使用計(jì)算屬性計(jì)算 -->
<p>{{fullName1}}</p>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
fastName: "Tracy",
lastName: "McGrady"
},
computed: {
fullName1: function(){
return this.fastName + " " + this.lastName
}
},
methods: {
fullName2: function(){
return this.fastName + " " + this.lastName
}
}
})
</script>
</html>
效果

統(tǒng)計(jì)價(jià)格案例
代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{totalPrice}}</p>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
bookes: [
{id: 100,name: 'Unix編程藝術(shù)',price: 119},
{id: 200,name: 'Java編程思想',price: 105},
{id: 300,name: '高并發(fā)編程',price: 98},
{id: 400,name: 'Spring5',price: 99},
]
},
computed: {
totalPrice: function(){
let result = 0;
// 普通循環(huán)
/* for(let i = 0;i < this.bookes.length;i++){
result += this.bookes[i].price;
} */
// 增強(qiáng)for循環(huán),i為索引
/* for(let i in this.bookes){
result += this.bookes[i].price;
} */
// ES6新增for循環(huán)直接獲取對(duì)象
for(let book of this.bookes){
result += book.price
}
return result;
}
}
})
</script>
</html>
getter和setter方法
介紹
計(jì)算屬性的完整寫(xiě)法其實(shí)是其中包含了getter和setter方法,聲明一個(gè)fullName對(duì)象,因?yàn)槲覀円话阒猾@取值,所以會(huì)將其省略寫(xiě)成上邊案例的方式,我們?cè)讷@取數(shù)據(jù)時(shí)會(huì)調(diào)用get方法,設(shè)置數(shù)據(jù)時(shí)會(huì)調(diào)用set方法
代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{fullName}}</p>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
firstName: "Tracy",
lastName: "McGrady"
},
// 計(jì)算屬性
computed: {
// 計(jì)算對(duì)象
fullName:{
// 設(shè)置數(shù)據(jù)
set: function(){
console.log('---');
},
// 獲取數(shù)據(jù)
get: function(){
return this.firstName + " " + this.lastName;
}
}
}
})
</script>
</html>
計(jì)算屬性緩存
這里就來(lái)回答一下上邊的methods和computed的區(qū)別的問(wèn)題,下方代碼分別使用插值語(yǔ)法、methods、計(jì)算屬性來(lái)做數(shù)據(jù)渲染。
代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 原始方式,該方式面對(duì)數(shù)據(jù)計(jì)算時(shí)比較繁瑣,不推薦使用 -->
<p>名字:{{name}} 工作:{{job}}</p>
<!-- methods方式,每獲取一次數(shù)據(jù)就調(diào)用一次函數(shù) -->
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<!-- computed方式,當(dāng)數(shù)據(jù)沒(méi)有發(fā)生變化時(shí),僅調(diào)用一次,會(huì)將數(shù)據(jù)進(jìn)行緩存 -->
<p>{{getInfo2}}</p>
<p>{{getInfo2}}</p>
<p>{{getInfo2}}</p>
<p>{{getInfo2}}</p>
<p>{{getInfo2}}</p>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
name: "麥迪",
job: "NBA球星"
},
methods: {
getInfo1: function(){
console.log("methods");
return "名字:" + this.name + "工作: " + this.job;
}
},
computed: {
getInfo2: function(){
console.log("computed");
return "名字:" + this.name + "工作: " + this.job;
}
}
})
</script>
</html>
圖解

結(jié)論
- methods和computed看起來(lái)都能實(shí)現(xiàn)我們的功能
- 計(jì)算屬性會(huì)進(jìn)行緩存,如果多次使用時(shí),計(jì)算屬性只會(huì)調(diào)用一次
監(jiān)視屬性
概述
我們可以使用watch來(lái)監(jiān)聽(tīng)指定數(shù)據(jù)的變換,進(jìn)而調(diào)用對(duì)應(yīng)的邏輯處理數(shù)據(jù)
代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<input type="text" v-model="firstName" />
<input type="text" v-model="lastName" />
<input type="text" v-model="fullName" />
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
const app = new Vue({
el: "#app",
data: {
firstName: "A",
lastName: "B",
fullName: "AB"
},
// 監(jiān)視屬性
watch: {
firstName(value) {
this.fullName = value + this.lastName
},
lastName(value) {
this.fullName = this.firstName + value
}
}
})
</script>
</html>
總結(jié)
監(jiān)聽(tīng)屬性要比計(jì)算屬性代碼多很多,計(jì)算屬性只需要計(jì)算數(shù)據(jù)即可,而監(jiān)聽(tīng)屬性需要監(jiān)聽(tīng)每個(gè)數(shù)據(jù)的變化
Vue生命周期
下圖展示了實(shí)例的生命周期。你不需要立馬弄明白所有的東西,不過(guò)隨著你的不斷學(xué)習(xí)和使用,它的參考價(jià)值會(huì)越來(lái)越高

生命周期大致分為三個(gè)階段 初始化階段 、 更新階段 、 死亡階段
初始化階段
該階段在new Vue 實(shí)例時(shí)調(diào)用,并且只調(diào)用一次
beforeCreate:創(chuàng)建之前調(diào)用函數(shù)
created:創(chuàng)建之后調(diào)用函數(shù)
之后進(jìn)行掛載和模板渲染
beforeMount:掛載前操作,去替換el選中的標(biāo)簽
Mounted:掛載完成,數(shù)據(jù)顯示在瀏覽器上
更新階段
當(dāng)數(shù)據(jù)發(fā)生變化時(shí)進(jìn)入該階段,該階段會(huì) 頻繁調(diào)用
beforeUpdate:當(dāng)數(shù)據(jù)發(fā)生修改時(shí)觸發(fā)
updated:虛擬DOM發(fā)生修改后,也就是數(shù)據(jù)修改后調(diào)用
死亡階段
死亡階段 也只 調(diào)用一次
beforeDestroy:銷毀之前
destroyed:銷毀
示例代碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<p v-show="isShow">{{message}}</p>
<p>{{isShow}}</p>
<button type="button" @click="destroyVM">取消布靈布靈</button>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
const app = new Vue({
el: "#app",
data: {
message: "若隱若現(xiàn)",
isShow: true
},
beforeCreate() {
console.log("beforeCreate");
},
created() {
console.log("create");
},
beforeMount() {
console.log("beforeMount");
},
mounted() {
console.log("mounted");
// 創(chuàng)建定時(shí)器
this.intervald = setInterval(()=>{
console.log("-------"+this.isShow);
this.isShow = !this.isShow;
},1000)
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeDestroy() {
console.log("beforeDestroy");
// 清除定時(shí)器
clearInterval(this.intervald)
},
destroyed() {
console.log("destroyed");
},
methods: {
// 干掉vm
destroyVM() {
// 調(diào)用銷毀函數(shù)
this.$destroy()
}
}
})
</script>
</html>
圖示如下,在頁(yè)面刷新時(shí)依次調(diào)用 beforeCreate、created、beforeMount、mounted,定時(shí)器運(yùn)行修改isShow數(shù)據(jù)時(shí)多次調(diào)用 beforeUpdate、updated,點(diǎn)擊按鈕調(diào)用注銷函數(shù),調(diào)用beforeDestroy、destroyed
總的來(lái)說(shuō)created、mounted、beforeDestroy較為常用
- created、mounted:發(fā)送ajax請(qǐng)求,啟動(dòng)定時(shí)器等異步任務(wù)
- beforeDestroy:做收尾工作,如:清除定時(shí)器

總結(jié)
到此這篇關(guān)于Vue.js中計(jì)算屬性、監(jiān)視屬性與生命周期的文章就介紹到這了,更多相關(guān)Vue計(jì)算屬性、監(jiān)視屬性與生命周期內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用yarn創(chuàng)建vite項(xiàng)目+vue3
這篇文章主要介紹了如何使用yarn創(chuàng)建vite項(xiàng)目+vue3,詳細(xì)介紹了使用vite創(chuàng)建vue3過(guò)程,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03
vue+Element?ui實(shí)現(xiàn)照片墻效果
這篇文章主要為大家詳細(xì)介紹了vue+Element?ui實(shí)現(xiàn)照片墻效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
vue根據(jù)權(quán)限動(dòng)態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)
這篇文章主要介紹了vue根據(jù)權(quán)限動(dòng)態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望杜大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

