計(jì)算屬性
computed:{
? ? ? ? ? ? ? ? fullName:{
? ? ? ? ? ? ? ? get(){
? ? ? ? ? ? ? ? ? ? ? ? return this.firstName + '-' + this.lastName
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? set(value){
????????????????????????const arr = value.split('-')
????????????????????????this.firstName = arr[0]
????????????????????????this.lastName = arr[1]
? ? ? ? ? ? ? ? ? }?
}
定義:要用的屬性不存在,需要通過已有屬性計(jì)算得來。
原理:底層借助了Objcet.defineproperty()方法提供的getter和setter。
get函數(shù)什么時(shí)候執(zhí)行?
????1)初次讀取時(shí)會(huì)執(zhí)行一次
????2)當(dāng)依賴的數(shù)據(jù)發(fā)生改變時(shí)會(huì)被再次調(diào)用
優(yōu)勢(shì):與methods實(shí)現(xiàn)相比,內(nèi)部有緩存機(jī)制(復(fù)用),效率更高,調(diào)試方便
備注:
????1)計(jì)算屬性最終會(huì)出現(xiàn)在vm上,直接讀取使用即可
????2)如果計(jì)算屬性要被修改,那必須寫set函數(shù)去響應(yīng)修改,且set中要引起計(jì)算時(shí)依賴的數(shù)據(jù)發(fā)生改變
????3)如果計(jì)算屬性確定不考慮修改,可以使用計(jì)算屬性的簡寫形式
????computed:{
????????? ? fullName(){
????????? ? return this.firstName + '-' + this.lastName
????????? ? }
? ? }
監(jiān)視屬性watch:
1、當(dāng)被監(jiān)視的屬性變化時(shí),回調(diào)函數(shù)自動(dòng)調(diào)用,進(jìn)行相關(guān)操作
2、監(jiān)視的屬性必須存在,才能進(jìn)行監(jiān)視
3、監(jiān)視有兩種寫法:
? ? 1)創(chuàng)建Vue時(shí)傳入watch配置
? ? 2)通過vm.$watch監(jiān)視
????vm.$watch('isHot',{
????????????immediate:true,
????????????handler(newValue,oldValue){
????????????console.log('isHot被修改了',newValue,oldValue)
????????}
????})
深度監(jiān)視:
Vue中的watch默認(rèn)不監(jiān)測(cè)對(duì)象內(nèi)部值的改變(一層)
在watch中配置deep:true可以監(jiān)測(cè)對(duì)象內(nèi)部值的改變(多層)
備注:
Vue自身可以監(jiān)測(cè)對(duì)象內(nèi)部值的改變,但Vue提供的watch默認(rèn)不可以
使用watch時(shí)根據(jù)監(jiān)視數(shù)據(jù)的具體結(jié)構(gòu),決定是否采用深度監(jiān)視
簡寫:
????watch:{
? ? ? ? ? ? //正常寫法
? ? ? ? ? ? isHot:{
????????????????handler(newValue,oldValue){
????????????????console.log('isHot被修改了',newValue,oldValue)
????????????????}
????????????},
? ? ? ? ? ? //簡寫
? ? ? ? ? ? isHot(newValue,oldValue){
????????????????????console.log('isHot被修改了',newValue,oldValue,this)
????????????}
? ? ?}
//正常寫法
vm.$watch('isHot',{
? ? ? handler(newValue,oldValue){
? ? ? ? ? console.log('isHot被修改了',newValue,oldValue)
? ? ? }
})
//簡寫
vm.$watch('isHot',function(newValue,oldValue){
? ? console.log('isHot被修改了',newValue,oldValue,this)
})
computed和watch之間的區(qū)別:
computed能完成的功能,watch都可以完成(可能寫起來更復(fù)雜)
computed:{
? ? ???? fullName(){
? ? ????????return this.firstName + '-' + this.lastName
? ? ???? }
? ? }
watch能完成的功能,computed不一定能完成,例如:watch可以進(jìn)行異步操作(定時(shí))
watch:{
????????firstName(val){
????????????setTimeout(()=>{
????????????????this.fullName = val + '-' + this.lastName
????????????},1000);
????????},
????????lastName(val){
????????????????this.fullName = this.firstName + '-' + val
????????}
}
兩個(gè)重要的小原則:
1)所有被Vue管理的函數(shù),最好寫成普通函數(shù),這樣this的指向才是 vm 或 組件實(shí)例對(duì)象
2)所有不被Vue所管理的函數(shù)(定時(shí)器的回調(diào)函數(shù)、ajax的回調(diào)函數(shù)等、Promise的回調(diào)函數(shù)),最好寫成箭頭函數(shù),這樣this的指向才是vm 或 組件實(shí)例對(duì)象。