日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

面试题: Vue中的 computed 和 watch的区别

發(fā)布時間:2025/3/20 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面试题: Vue中的 computed 和 watch的区别 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

computed

computed看上去是方法,但是實際上是計算屬性,它會根據(jù)你所依賴的數(shù)據(jù)動態(tài)顯示新的計算結(jié)果。計算結(jié)果會被緩存,computed的值在getter執(zhí)行后是會緩存的,只有在它依賴的屬性值改變之后,下一次獲取computed的值時才會重新調(diào)用對應(yīng)的getter來計算


1)下面是一個比較經(jīng)典簡單的案例

<template><div class="hello">{{fullName}}</div> </template><script> export default {data() {return {firstName: '飛',lastName: "旋"}},props: {msg: String},computed: {fullName() {return this.firstName + ' ' + this.lastName}} } </script>復(fù)制代碼

注意

在Vue的 template模板內(nèi)({{}})是可以寫一些簡單的js表達(dá)式的很便利,如上直接計算 {{this.firstName + ' ' + this.lastName}},因為在模版中放入太多聲明式的邏輯會讓模板本身過重,尤其當(dāng)在頁面中使用大量復(fù)雜的邏輯表達(dá)式處理數(shù)據(jù)時,會對頁面的可維護性造成很大的影響,而 computed 的設(shè)計初衷也正是用于解決此類問題。

應(yīng)用場景

適用于重新計算比較費時不用重復(fù)數(shù)據(jù)計算的環(huán)境。所有 getter 和 setter 的 this 上下文自動地綁定為 Vue 實例。如果一個數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個數(shù)據(jù)設(shè)計為computed


watch

watcher 更像是一個 data 的數(shù)據(jù)監(jiān)聽回調(diào),當(dāng)依賴的 data 的數(shù)據(jù)變化,執(zhí)行回調(diào),在方法中會傳入 newVal 和 oldVal。可以提供輸入值無效,提供中間值 特場景。Vue 實例將會在實例化時調(diào)用 $watch(),遍歷 watch 對象的每一個屬性。如果你需要在某個數(shù)據(jù)變化時做一些事情,使用watch。<template><div class="hello">{{fullName}}<button @click="setNameFun">click</button></div> </template><script> export default {data() {return {firstName: '飛',lastName: "旋"}},props: {msg: String},methods: {setNameFun() {this.firstName = "大";this.lastName = "熊"}},computed: {fullName() {return this.firstName + ' ' + this.lastName}},watch: {firstName(newval,oldval) {console.log(newval)console.log(oldval)}} } </script>復(fù)制代碼


總結(jié):?

1.如果一個數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個數(shù)據(jù)設(shè)計為computed的 ?

2.如果你需要在某個數(shù)據(jù)變化時做一些事情,使用watch來觀察這個數(shù)據(jù)變化

轉(zhuǎn)載于:https://juejin.im/post/5c9990d6f265da60ea146d21

總結(jié)

以上是生活随笔為你收集整理的面试题: Vue中的 computed 和 watch的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。