Vue中的 computed 和 watch的区别
生活随笔
收集整理的這篇文章主要介紹了
Vue中的 computed 和 watch的区别
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
computed
computed看上去是方法,但是實(shí)際上是計(jì)算屬性,它會(huì)根據(jù)你所依賴的數(shù)據(jù)動(dòng)態(tài)顯示新的計(jì)算結(jié)果。計(jì)算結(jié)果會(huì)被緩存,computed的值在getter執(zhí)行后是會(huì)緩存的,只有在它依賴的屬性值改變之后,下一次獲取computed的值時(shí)才會(huì)重新調(diào)用對(duì)應(yīng)的getter來計(jì)算?
1)下面是一個(gè)比較經(jīng)典簡(jiǎn)單的案例
<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)({{}})是可以寫一些簡(jiǎn)單的js表達(dá)式的很便利,如上直接計(jì)算 {{this.firstName + ' ' + this.lastName}},因?yàn)樵谀0嬷蟹湃胩嗦暶魇降倪壿嫊?huì)讓模板本身過重,尤其當(dāng)在頁面中使用大量復(fù)雜的邏輯表達(dá)式處理數(shù)據(jù)時(shí),會(huì)對(duì)頁面的可維護(hù)性造成很大的影響,而 computed 的設(shè)計(jì)初衷也正是用于解決此類問題。應(yīng)用場(chǎng)景
適用于重新計(jì)算比較費(fèi)時(shí)不用重復(fù)數(shù)據(jù)計(jì)算的環(huán)境。所有 getter 和 setter 的 this 上下文自動(dòng)地綁定為 Vue 實(shí)例。如果一個(gè)數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個(gè)數(shù)據(jù)設(shè)計(jì)為computed?
watch
watcher 更像是一個(gè) data 的數(shù)據(jù)監(jiān)聽回調(diào),當(dāng)依賴的 data 的數(shù)據(jù)變化,執(zhí)行回調(diào),在方法中會(huì)傳入 newVal 和 oldVal。可以提供輸入值無效,提供中間值 特場(chǎng)景。Vue 實(shí)例將會(huì)在實(shí)例化時(shí)調(diào)用 $watch(),遍歷 watch 對(duì)象的每一個(gè)屬性。如果你需要在某個(gè)數(shù)據(jù)變化時(shí)做一些事情,使用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.如果一個(gè)數(shù)據(jù)依賴于其他數(shù)據(jù),那么把這個(gè)數(shù)據(jù)設(shè)計(jì)為computed的 ?
2.如果你需要在某個(gè)數(shù)據(jù)變化時(shí)做一些事情,使用watch來觀察這個(gè)數(shù)據(jù)變化
作者:李赫feixuan
鏈接:https://juejin.im/post/5c9990d6f265da60ea146d21
總結(jié)
以上是生活随笔為你收集整理的Vue中的 computed 和 watch的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea默认全文搜索快捷键
- 下一篇: vue下的props,data