面试题: Vue中的 computed 和 watch的区别
生活随笔
收集整理的這篇文章主要介紹了
面试题: Vue中的 computed 和 watch的区别
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
computed
computed看上去是方法,但是實(shí)際上是計算屬性,它會根據(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}},因?yàn)樵谀0嬷蟹湃胩嗦暶魇降倪壿嫊屇0灞旧磉^重,尤其當(dāng)在頁面中使用大量復(fù)雜的邏輯表達(dá)式處理數(shù)據(jù)時,會對頁面的可維護(hù)性造成很大的影響,而 computed 的設(shè)計初衷也正是用于解決此類問題。應(yīng)用場景
適用于重新計算比較費(fèi)時不用重復(fù)數(shù)據(jù)計算的環(huán)境。所有 getter 和 setter 的 this 上下文自動地綁定為 Vue 實(shí)例。如果一個數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個數(shù)據(jù)設(shè)計為computedwatch
watcher 更像是一個 data 的數(shù)據(jù)監(jiān)聽回調(diào),當(dāng)依賴的 data 的數(shù)據(jù)變化,執(zhí)行回調(diào),在方法中會傳入 newVal 和 oldVal。可以提供輸入值無效,提供中間值 特場景。Vue 實(shí)例將會在實(shí)例化時調(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codis的dashboard异常退出后
- 下一篇: Oracle 裁员史:技术人死于重组,卒