Vue.js中的計算屬性、監(jiān)視屬性與生命周期詳解
前言
本章節(jié)咱們來說一下Vue中兩個非常重要的計算屬性、監(jiān)視屬性和生命周期,不廢話直接上干貨
計算屬性
計算屬性介紹
在模板中可以直接通過插值語法顯示一些data中的數(shù)據(jù),有些情況下我們需要對數(shù)據(jù)進行轉(zhuǎn)化或者計算后顯示,我們可以使用computed選項來計算,這時有些小伙伴可能就會問,我直接定義函數(shù)再調(diào)用不就行了,為什么還要整一個計算屬性呢?這個問題在下邊再做解釋,我們先來看一下計算屬性怎么用!
入門案例
需求
將人的姓和名拼接在一起
代碼
<!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>
<!-- 在模板語法中進行計算 -->
<p>{{fastName + " " + lastName}}</p>
<!-- 調(diào)用函數(shù)計算 -->
<p v-text="fullName2()"></p>
<!-- 使用計算屬性計算 -->
<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)計價格案例
代碼
<!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;
} */
// 增強for循環(huán),i為索引
/* for(let i in this.bookes){
result += this.bookes[i].price;
} */
// ES6新增for循環(huán)直接獲取對象
for(let book of this.bookes){
result += book.price
}
return result;
}
}
})
</script>
</html>
getter和setter方法
介紹
計算屬性的完整寫法其實是其中包含了getter和setter方法,聲明一個fullName對象,因為我們一般只獲取值,所以會將其省略寫成上邊案例的方式,我們在獲取數(shù)據(jù)時會調(diào)用get方法,設(shè)置數(shù)據(jù)時會調(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"
},
// 計算屬性
computed: {
// 計算對象
fullName:{
// 設(shè)置數(shù)據(jù)
set: function(){
console.log('---');
},
// 獲取數(shù)據(jù)
get: function(){
return this.firstName + " " + this.lastName;
}
}
}
})
</script>
</html>
計算屬性緩存
這里就來回答一下上邊的methods和computed的區(qū)別的問題,下方代碼分別使用插值語法、methods、計算屬性來做數(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">
<!-- 原始方式,該方式面對數(shù)據(jù)計算時比較繁瑣,不推薦使用 -->
<p>名字:{{name}} 工作:{{job}}</p>
<!-- methods方式,每獲取一次數(shù)據(jù)就調(diào)用一次函數(shù) -->
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<p>{{getInfo1()}}</p>
<!-- computed方式,當數(shù)據(jù)沒有發(fā)生變化時,僅調(diào)用一次,會將數(shù)據(jù)進行緩存 -->
<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看起來都能實現(xiàn)我們的功能
- 計算屬性會進行緩存,如果多次使用時,計算屬性只會調(diào)用一次
監(jiān)視屬性
概述
我們可以使用watch來監(jiān)聽指定數(shù)據(jù)的變換,進而調(diào)用對應(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)聽屬性要比計算屬性代碼多很多,計算屬性只需要計算數(shù)據(jù)即可,而監(jiān)聽屬性需要監(jiān)聽每個數(shù)據(jù)的變化
Vue生命周期
下圖展示了實例的生命周期。你不需要立馬弄明白所有的東西,不過隨著你的不斷學習和使用,它的參考價值會越來越高

生命周期大致分為三個階段 初始化階段 、 更新階段 、 死亡階段
初始化階段
該階段在new Vue 實例時調(diào)用,并且只調(diào)用一次
beforeCreate:創(chuàng)建之前調(diào)用函數(shù)
created:創(chuàng)建之后調(diào)用函數(shù)
之后進行掛載和模板渲染
beforeMount:掛載前操作,去替換el選中的標簽
Mounted:掛載完成,數(shù)據(jù)顯示在瀏覽器上
更新階段
當數(shù)據(jù)發(fā)生變化時進入該階段,該階段會 頻繁調(diào)用
beforeUpdate:當數(shù)據(jù)發(fā)生修改時觸發(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)建定時器
this.intervald = setInterval(()=>{
console.log("-------"+this.isShow);
this.isShow = !this.isShow;
},1000)
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeDestroy() {
console.log("beforeDestroy");
// 清除定時器
clearInterval(this.intervald)
},
destroyed() {
console.log("destroyed");
},
methods: {
// 干掉vm
destroyVM() {
// 調(diào)用銷毀函數(shù)
this.$destroy()
}
}
})
</script>
</html>
圖示如下,在頁面刷新時依次調(diào)用 beforeCreate、created、beforeMount、mounted,定時器運行修改isShow數(shù)據(jù)時多次調(diào)用 beforeUpdate、updated,點擊按鈕調(diào)用注銷函數(shù),調(diào)用beforeDestroy、destroyed
總的來說created、mounted、beforeDestroy較為常用
- created、mounted:發(fā)送ajax請求,啟動定時器等異步任務(wù)
- beforeDestroy:做收尾工作,如:清除定時器

總結(jié)
到此這篇關(guān)于Vue.js中計算屬性、監(jiān)視屬性與生命周期的文章就介紹到這了,更多相關(guān)Vue計算屬性、監(jiān)視屬性與生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue根據(jù)權(quán)限動態(tài)渲染按鈕、組件等的函數(shù)式組件實現(xiàn)
這篇文章主要介紹了vue根據(jù)權(quán)限動態(tài)渲染按鈕、組件等的函數(shù)式組件實現(xiàn)方式,具有很好的參考價值,希望杜大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

