實(shí)例詳解vue.js淺度監(jiān)聽和深度監(jiān)聽及watch用法
第一個淺度監(jiān)聽:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/vue.js"></script> </head> <body> <div id="app"> <p>{{a}}</p> <p>{}</p> </div> <script> var vm=new Vue({ el:"#app", data:{ a:10, b:15 } }); vm.$watch("a",function(){ alert('a變化了'); this.b=100; }); document.onclick=function(){ vm.a=2 } </script> </body> </html>
第二個深度監(jiān)聽
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/vue.js"></script> </head> <body> <div id="app"> <p>{{a|json}}</p> <p>{}</p> </div> <script> var vm = new Vue({ el: "#app", data: { a: { id: "1", title: "width" }, b: 15 } }); vm.$watch("a", function() { alert('a變化了'); this.b = 100; }, { deep: true }); document.onclick = function() { vm.a.id = "2"; } </script> </body> </html>
ps:下面看下vue中watch用法
對應(yīng)一個對象,鍵是觀察表達(dá)式,值是對應(yīng)回調(diào)。值也可以是方法名,或者是對象,包含選項(xiàng)。在實(shí)例化時為每個鍵調(diào)用 $watch() ;
//使用官方vue-cli腳手架書寫 <template> //觀察數(shù)據(jù)為字符串或數(shù)組 <input v-model="example0"/> <input v-model="example1"/> /當(dāng)單觀察數(shù)據(jù)examples2為對象時,如果鍵值發(fā)生變化,為了監(jiān)聽到數(shù)據(jù)變化,需要添加deep:true參數(shù) <input v-model="example2.inner0"/> </template> <script> export default { data(){ return { example0:"", example1:"", example2:{ inner0:1, innner1:2 } } }, watch:{ example0(curVal,oldVal){ console.log(curVal,oldVal); }, example1:'a',//值可以為methods的方法名 example2:{ //注意:當(dāng)觀察的數(shù)據(jù)為對象或數(shù)組時,curVal和oldVal是相等的,因?yàn)檫@兩個形參指向的是同一個數(shù)據(jù)對象 handler(curVal,oldVal){ conosle.log(curVal,oldVal) }, deep:true } }, methods:{ a(curVal,oldVal){ conosle.log(curVal,oldVal) } } } </script>
相關(guān)文章
vue使用jsMind思維導(dǎo)圖的實(shí)戰(zhàn)指南
jsMind是一個顯示/編輯思維導(dǎo)圖的純javascript類庫,其基于 html5的canvas進(jìn)行設(shè)計(jì),這篇文章主要給大家介紹了關(guān)于vue使用jsMind思維導(dǎo)圖的相關(guān)資料,需要的朋友可以參考下2023-01-01Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗(yàn)方式
這篇文章主要介紹了Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗(yàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06詳解vite2.0配置學(xué)習(xí)(typescript版本)
這篇文章主要介紹了詳解vite2.0配置學(xué)習(xí)(typescript版本),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02vue3中配置文件vue.config.js不生效的解決辦法
這篇文章主要介紹了vue3中配置文件vue.config.js不生效的解決辦法,文中通過代碼示例講解的非常詳細(xì),對大家解決問題有一定的幫助,需要的朋友可以參考下2024-05-05vue基于echarts實(shí)現(xiàn)立體柱形圖
這篇文章主要為大家詳細(xì)介紹了vue基于echarts實(shí)現(xiàn)立體柱形圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09vue(element ui)使用websocket及心跳檢測方式
這篇文章主要介紹了vue(element ui)使用websocket及心跳檢測方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07