老生常談Vue中的偵聽器watch
更新時間:2022年10月15日 12:09:33 作者:東非不開森
開發(fā)中我們在data返回的對象中定義了數(shù)據(jù),這個數(shù)據(jù)通過插值語法等方式綁定到template中,這篇文章主要介紹了Vue中的偵聽器watch,需要的朋友可以參考下
一、偵聽器watch
(思維導(dǎo)圖不太完善,因為是按照自己看懂的方式記的,如有錯誤,還請指正)
1.1.初識偵聽器watch
??
watch:觀看,監(jiān)視
那么什么是偵聽器watch
呢
- 開發(fā)中我們在
data
返回的對象中定義了數(shù)據(jù),這個數(shù)據(jù)通過插值語法等方式綁定到template
中; - 當(dāng)數(shù)據(jù)變化時,
template
會自動進(jìn)行更新來顯示最新的數(shù)據(jù); - 但是在某些情況下,我們希望在代碼邏輯中監(jiān)聽某個數(shù)據(jù)的變化,這個時候就需要用偵聽器
watch
來完成了;
1.2.Vue的data的watch
??
案例:
- 我們希望用戶在input中輸入一個問題;
- 每當(dāng)用戶輸入了最新的內(nèi)容,我們就獲取到最新的內(nèi)容,并且使用該問題去服務(wù)器查詢答案;
- 那么,我們就需要實時的去獲取最新的數(shù)據(jù)變化;
- 此時就要用到偵聽器watch去監(jiān)聽數(shù)據(jù)是否發(fā)生變化
const app = Vue.createApp({ data() { return { message: "Hello Vue", info: { name: "kk", age: 18 }, }; }, methods: { changeMessage() { this.message = "hello kk"; this.info = { name: "kk" }; }, }, watch: { // 1.默認(rèn)有兩個參數(shù),newValue/oldValue message(newValue, oldVale) { console.log("message數(shù)據(jù)發(fā)生了變化", newValue, oldValue); }, info(newValue, oldValue) { // 2.如果是對象類型,那么拿到的是代理對象 console.log("info數(shù)據(jù)發(fā)生了變化", newValue, oldValue); console.log(newValue.name, oldValue.name); // 3.獲取原始對象 console.log({ ...newValue });
1.3.Vue的watch偵聽選項
??
- 創(chuàng)建一個對象,賦值給info
- 點擊按鈕的時候會修改info.name的值
- 此時使用watch并不能偵聽info,因為默認(rèn)情況下,watch只是在偵聽info的引用變化,對于內(nèi)部屬性的變化是不會做出響應(yīng)的
- 所以我們可以使用deep深度監(jiān)聽
- 希望一開始的就會立即執(zhí)行一次:這個時候我們使用immediate選項;無論數(shù)據(jù)是否變化,偵聽的函數(shù)都會有限執(zhí)行一次的
<div id="app"> <h2>{{info.name}}</h2> <button @click="changeInfo">修改info</button> </div>
const app = Vue.createApp({ data() { return { info: { name: "kk", age: 18 }, }; }, methods: { changeInfo() { // 創(chuàng)建一個對象,賦值給info this.info = { name: "kk" }; // 直接修改對象里的一個屬性 this.info.name = "kk"; }, }, watch: { // 默認(rèn)watch監(jiān)聽不會進(jìn)行深度監(jiān)聽 info(newValue, oldValue) { console.log("偵聽到info改變", newValue, oldValue); }, // 進(jìn)行深度監(jiān)聽 info: { handler(newValue, oldValue) { console.log("偵聽到info改變", newValue, oldValue); console.log(newValue === oldValue); }, // 監(jiān)聽器選項 // info進(jìn)行深度監(jiān)聽 deep: true, // 第一次渲染直接執(zhí)行一次監(jiān)聽器 immediate: true, }, }, "info.name": function (newValue, oldValue) { console.log("name發(fā)生改變", newValue, oldValue); }, }); app.mount("#app");
到此這篇關(guān)于Vue中的偵聽器watch的文章就介紹到這了,更多相關(guān)Vue偵聽器watch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
教你使用vue-autofit 一行代碼搞定自適應(yīng)可視化大屏
這篇文章主要為大家介紹了使用vue-autofit 一行代碼搞定自適應(yīng)可視化大屏教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05