Vue踩坑之旅(一)—— 数组、对象的监听
作為一個(gè)接觸 vue 才一個(gè)多月的小白,馬上就接手基于 vue 的大型商城項(xiàng)目,其間真是跌跌撞撞踩了好多坑(o(╥﹏╥)o)。在此寫下自己的踩坑之旅,希望給跟我一樣還在自學(xué) vue 的同學(xué)一些幫助,另外大佬如果有更好的解決辦法,請(qǐng)不吝賜教。
watch 偵聽屬性有如下屬性:1. handler:監(jiān)聽數(shù)組或?qū)ο蟮膶傩詴r(shí)用到的方法
2. deep:深度監(jiān)聽,為了發(fā)現(xiàn)對(duì)象內(nèi)部值的變化,可以在選項(xiàng)參數(shù)中指定 deep:true 。
3. immediate: 在選項(xiàng)參數(shù)中指定 immediate: true 將立即以表達(dá)式的當(dāng)前值觸發(fā)回調(diào)
4. tips: 只要bet中的屬性發(fā)生變化(可被監(jiān)測到的),便會(huì)執(zhí)行handler函數(shù);如果想監(jiān)測具體的屬性變化,如pokerHistory變化時(shí),才執(zhí)行handler函數(shù),則可以利用計(jì)算屬性computed做中間層。
watch 偵聽屬性其實(shí)用得挺多的,但是我之前只是簡單的應(yīng)用了:
data() {return { frontPoints: 0 } }, watch: {frontPoints(newValue, oldValue) {console.log(newValue)} }復(fù)制代碼但是現(xiàn)在項(xiàng)目中需要偵聽的屬性結(jié)構(gòu)比較復(fù)雜:
data() { return { commentForm: { OrderId: null, ShopScore: null,ScoreDetailList: [// {// CommodityScore: null,// OrderDetailId: null,// Content: '',// FileIdLIst: []// },]}} }復(fù)制代碼如果我想監(jiān)聽?ShopScore 和 未知長度的數(shù)組? ScoreDetailList
watch: {'commentForm.ScoreDetailList': {function(val) {console.log(val)},deep: true},'commentForm.ShopScore': function (val) {console.log(val)} }復(fù)制代碼此時(shí)就會(huì)報(bào)錯(cuò):
使用深度監(jiān)聽 deep: true 也會(huì)報(bào)同樣的錯(cuò)誤。
之后我就總結(jié)了幾種情況:
1. watch 普通屬性(非數(shù)組和對(duì)象)
2. watch 數(shù)組(不能使用?deep: true?)
data() {return {Array1: new Array(11).fill(0)} }, watch: {Array1: { handler(newValue, oldValue) {newValue.forEach((item, i) => {if (item !== oldValue[i]) {console.log(newValue) }}}, } }復(fù)制代碼3. watch 對(duì)象
data() {return {obj: {age: 53,name: 'lakey'}} }, watch: {obj: {handler(newValue, oldValue) {console.log(newValue) },deep: true} }復(fù)制代碼4. watch 對(duì)象具體屬性
這里有兩個(gè)方案,已是直接寫具體屬性:
data() {return {obj: {age: 53,name: 'lakey'}} }, watch: {'obj.name': {handler(newValue, oldValue) {console.log(newValue) }} }復(fù)制代碼另一種,是活用計(jì)算屬性 computed
data() {return {obj: {age: 53,name: 'lakey'}} }, computed: {obj() {return this.obj.name} }, watch: {name(newValue, oldValue) {console.log(newValue)} } 復(fù)制代碼------------------------------補(bǔ)上我的項(xiàng)目的解決辦法----------------------------------------
轉(zhuǎn)載于:https://juejin.im/post/5d02009ae51d4510bf1d6665
總結(jié)
以上是生活随笔為你收集整理的Vue踩坑之旅(一)—— 数组、对象的监听的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS启动不显示图形界面直接进入命
- 下一篇: erlang节点互相ping,一个能pi