日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁 > 科技  > 軟件

Vue3 學(xué)習(xí)筆記,如何使用 Watch 監(jiān)聽數(shù)據(jù)變化

來源: 責(zé)編: 時(shí)間:2023-12-14 16:38:15 244觀看
導(dǎo)讀大家好,本篇文章我們繼續(xù)學(xué)習(xí)和 Vue 相關(guān)的內(nèi)容,今天我們歸納總結(jié)下如何使用 watch 監(jiān)聽組件中的數(shù)據(jù)變化,以及 computed 和 watch 的區(qū)別。什么是 watch,以及如何使用?watch 是 Vue.js 中用于監(jiān)聽數(shù)據(jù)變化的一種機(jī)制。它

8TY28資訊網(wǎng)——每日最新資訊28at.com

大家好,本篇文章我們繼續(xù)學(xué)習(xí)和 Vue 相關(guān)的內(nèi)容,今天我們歸納總結(jié)下如何使用 watch 監(jiān)聽組件中的數(shù)據(jù)變化,以及 computed 和 watch 的區(qū)別。8TY28資訊網(wǎng)——每日最新資訊28at.com

什么是 watch,以及如何使用?

watch 是 Vue.js 中用于監(jiān)聽數(shù)據(jù)變化的一種機(jī)制。它允許我們在數(shù)據(jù)發(fā)生變化時(shí)執(zhí)行特定的操作。8TY28資訊網(wǎng)——每日最新資訊28at.com

在 Vue 中使用 watch 的方法如下:8TY28資訊網(wǎng)——每日最新資訊28at.com

在 Vue 組件中,定義一個(gè) watch 對象,其中包含要監(jiān)聽的數(shù)據(jù)屬性以及對應(yīng)的回調(diào)函數(shù)。8TY28資訊網(wǎng)——每日最新資訊28at.com

watch: {  dataName: function(newValue, oldValue) {    // code  }}

其中,dataName 是要監(jiān)聽的數(shù)據(jù)名稱,newValue 是新的值,oldValue 是舊的值。8TY28資訊網(wǎng)——每日最新資訊28at.com

在 Vue 實(shí)例中,使用 $watch() 方法進(jìn)行監(jiān)聽8TY28資訊網(wǎng)——每日最新資訊28at.com

vm.$watch('someData', function(newVal, oldVal) {  // do something with newVal});

注意:watch 回調(diào)函數(shù)會(huì)在偵聽的數(shù)據(jù)發(fā)生變化時(shí)立即執(zhí)行,而 computed 屬性只有在其依賴的數(shù)據(jù)發(fā)生變化時(shí)才會(huì)計(jì)算。8TY28資訊網(wǎng)——每日最新資訊28at.com

watch 通常用于監(jiān)聽一個(gè)數(shù)據(jù)的變化并執(zhí)行復(fù)雜的業(yè)務(wù)邏輯,例如在某個(gè)數(shù)據(jù)變化后需要進(jìn)行 HTTP 請求或者調(diào)用其他函數(shù)。8TY28資訊網(wǎng)——每日最新資訊28at.com

下面是一個(gè)簡單的 watch 的例子:8TY28資訊網(wǎng)——每日最新資訊28at.com

<template>  <div>    <input v-model="message" type="text" placeholder="請輸入內(nèi)容">    <p>{{ message }}</p>  </div></template><script>export default {  data() {    return {      message: '',    }  },  watch: {    message: function (newVal, oldVal) {      console.log('message changed from ' + oldVal + ' to ' + newVal)    }  },}</script>

在這個(gè)例子中,我們使用了 watch 來監(jiān)聽 message 的變化,并在數(shù)據(jù)變化時(shí)打印出更改前后的值。8TY28資訊網(wǎng)——每日最新資訊28at.com

當(dāng)然,watch 還可以接收一個(gè)對象,其中可以定義多個(gè)監(jiān)聽器。這里有一個(gè)例子,它監(jiān)聽了多個(gè)數(shù)據(jù):8TY28資訊網(wǎng)——每日最新資訊28at.com

watch: {  firstName: function (newVal, oldVal) {    console.log('firstName changed from ' + oldVal + ' to ' + newVal)  },  lastName: function (newVal, oldVal) {    console.log('lastName changed from ' + oldVal + ' to ' + newVal)  }}

一些高級(jí)用法介紹

深度觀察 (deep: true):如果你希望對對象內(nèi)部屬性的變化進(jìn)行監(jiān)聽,可以使用 deep: true 選項(xiàng)。8TY28資訊網(wǎng)——每日最新資訊28at.com

data() {  user: {    name: 'John',    age: 25  }},watch: {  'user.name': function (val) {    console.log('user name changed:', val)  }}

在這個(gè)例子中,我們監(jiān)聽了 user 對象中的 name 屬性,當(dāng)該屬性變化時(shí),會(huì)執(zhí)行回調(diào)函數(shù)。8TY28資訊網(wǎng)——每日最新資訊28at.com

設(shè)置初始值 (immediate: true):如果你希望 watch 在組件創(chuàng)建時(shí)立即執(zhí)行一次,可以使用 immediate: true 選項(xiàng)。8TY28資訊網(wǎng)——每日最新資訊28at.com

data() {    count: 0},watch: {    count: {        handler: function (val, oldVal) {            console.log('count changed');        },        immediate: true    }}

異步處理 (handler):watch 的回調(diào)函數(shù)是異步執(zhí)行的,這意味著如果有多個(gè)值在短時(shí)間內(nèi)發(fā)生變化,回調(diào)函數(shù)只會(huì)在這些變化結(jié)束后執(zhí)行一次。8TY28資訊網(wǎng)——每日最新資訊28at.com

watch: {  searchText: function (val) {    this.searching = true    setTimeout(() => {      this.searchData(val)      this.searching = false    }, 500)  }}

在這個(gè)例子中,我們監(jiān)聽了 searchText 屬性,并在數(shù)據(jù)變化后延遲 500 毫秒執(zhí)行搜索操作。8TY28資訊網(wǎng)——每日最新資訊28at.com

使用 watch 觀察器實(shí)現(xiàn)自動(dòng)保存。8TY28資訊網(wǎng)——每日最新資訊28at.com

data() {  content: ''},watch: {  content: function (val) {    localStorage.setItem('content', val)  }}

在這個(gè)例子中,我們監(jiān)聽了 content 屬性,并在數(shù)據(jù)變化時(shí)自動(dòng)保存到本地存儲(chǔ)中。8TY28資訊網(wǎng)——每日最新資訊28at.com

應(yīng)用場景介紹

watch 監(jiān)聽器還有許多其他的應(yīng)用場景,例如:8TY28資訊網(wǎng)——每日最新資訊28at.com

  • 在表單輸入時(shí)進(jìn)行驗(yàn)證,并顯示錯(cuò)誤消息。
  • 在表格中進(jìn)行排序和過濾。
  • 在地圖上實(shí)時(shí)顯示用戶位置。
  • 監(jiān)聽路由變化并執(zhí)行相應(yīng)操作。
  • 監(jiān)聽窗口大小變化并調(diào)整布局。
  • 監(jiān)聽滾動(dòng)事件并實(shí)現(xiàn)懶加載。
  • ……

1、在表單輸入時(shí)進(jìn)行驗(yàn)證,并顯示錯(cuò)誤消息

<template>  <form>    <label>      Email:      <input v-model="email" @keyup="validateEmail"/>    </label>    <p v-if="error">{{ error }}</p>  </form></template><script>export default {  data() {    return {      email: '',      error: ''    }  },  watch: {    email: {      immediate: true,      handler(val) {        if (!val.includes('@')) {          this.error = 'Invalid email address'        } else {          this.error = ''        }      }    }  }}</script>

2、在地圖上實(shí)時(shí)顯示用戶位置

<template>  <div>    <div id="map"></div>  </div></template><script>export default {  data() {    return {      userLocation: {        lat: 0,        lng: 0      },      map: null    }  },  mounted() {    this.map = new google.maps.Map(document.getElementById("map"), {      center: { lat: 0, lng: 0 },      zoom: 8    });    navigator.geolocation.getCurrentPosition(position => {      this.userLocation = {        lat: position.coords.latitude,        lng: position.coords.longitude      }    });  },  watch: {    userLocation: {      deep: true,      handler(val) {        this.map.setCenter(val);        new google.maps.Marker({          position: val,          map: this.map        });      }    }  }}</script>

在這個(gè)示例中,我們使用了 watch 來監(jiān)聽 userLocation 的變化,在用戶位置發(fā)生變化時(shí),使用 setCenter 方法將地圖中心設(shè)置為用戶當(dāng)前位置,并使用 google maps API 在地圖上添加一個(gè)標(biāo)記,顯示用戶當(dāng)前位置。8TY28資訊網(wǎng)——每日最新資訊28at.com

注意:這個(gè)例子需要引入 google maps 的 js 文件。8TY28資訊網(wǎng)——每日最新資訊28at.com

3、監(jiān)聽路由變化并執(zhí)行相應(yīng)操作

<template>  <!-- 省略 --></template><script>export default {  watch: {    $route(to, from) {      // 根據(jù)路由變化執(zhí)行相應(yīng)操作      if (to.path === '/home') {        this.getHomeData()      } else if (to.path === '/about') {        this.getAboutData()      }    }  },  methods: {    getHomeData() {      // 獲取首頁數(shù)據(jù)    },    getAboutData() {      // 獲取關(guān)于頁數(shù)據(jù)    }  }}</script>

4、監(jiān)聽窗口大小變化并調(diào)整布局

<template>  <!-- 省略 --></template><script>export default {  data() {    return {      windowWidth: 0    }  },  created() {    this.windowWidth = window.innerWidth  },  watch: {    windowWidth(newWidth, oldWidth) {      // 監(jiān)聽窗口大小變化并調(diào)整布局      if (newWidth < 768) {        // 小屏幕布局      } else {        // 大屏幕布局      }    }  },  mounted() {    window.addEventListener('resize', () => {      this.windowWidth = window.innerWidth    })  }}</script>

5、監(jiān)聽滾動(dòng)事件并實(shí)現(xiàn)懶加載

<template>  <div class="container" ref="container" @scroll="handleScroll">    <img v-for="(item, index) in images" :key="index" :src="item.src" v-show="item.isLoaded" />  </div></template><script>export default {  data() {    return {      images: [        { src: 'image1.jpg', isLoaded: false },        { src: 'image2.jpg', isLoaded: false },        { src: 'image3.jpg', isLoaded: false },        // ...      ]    }  },  mounted() {    // 初始化加載第一屏圖片    this.lazyLoad();  },  methods: {    handleScroll() {      this.lazyLoad();    },    lazyLoad() {      const container = this.$refs.container;      const imageList = Array.from(container.querySelectorAll('img'));      // 遍歷圖片列表,如果圖片進(jìn)入了可視區(qū)域,就加載      imageList.forEach(img => {        if (this.isInViewport(img)) {          img.src = img.dataset.src;          img.isLoaded = true;        }      });    },    isInViewport(img) {      // 獲取圖片相對于視口的位置      const rect = img.getBoundingClientRect();      // 判斷圖片是否進(jìn)入了可視區(qū)域      return rect.top < window.innerHeight && rect.bottom > 0;    }  },  watch: {    images: {      handler: function(newVal, oldVal) {        // 每當(dāng)圖片加載完成時(shí),就移除已加載圖片的 isLoaded 屬性        newVal.forEach((item, index) => {          if (item.isLoaded) {            this.$set(this.images[index], 'isLoaded', false);          }        });      },      deep: true    }  }}</script>

注意:需要注意的是,在這個(gè)案例中,因?yàn)閕mages數(shù)組中的對象被改變了,所以需要設(shè)置deep: true來監(jiān)聽對象8TY28資訊網(wǎng)——每日最新資訊28at.com

總之,watch 是一個(gè)非常強(qiáng)大和靈活的功能,它可以在數(shù)據(jù)變化時(shí)執(zhí)行任何操作,并且可以與 computed 計(jì)算屬性配合使用,來實(shí)現(xiàn)更復(fù)雜的邏輯。8TY28資訊網(wǎng)——每日最新資訊28at.com

computed 和 watch 的區(qū)別

watch和computed都可以監(jiān)聽Vue實(shí)例中的數(shù)據(jù)變化,但是它們有著明顯的不同。8TY28資訊網(wǎng)——每日最新資訊28at.com

watch8TY28資訊網(wǎng)——每日最新資訊28at.com

computed8TY28資訊網(wǎng)——每日最新資訊28at.com

用于監(jiān)聽某個(gè)特定的數(shù)據(jù)變化。8TY28資訊網(wǎng)——每日最新資訊28at.com

用于計(jì)算屬性,可以計(jì)算出一個(gè)新的值。8TY28資訊網(wǎng)——每日最新資訊28at.com

每次數(shù)據(jù)變化都會(huì)觸發(fā)回調(diào)函數(shù)。8TY28資訊網(wǎng)——每日最新資訊28at.com

僅在相關(guān)依賴發(fā)生改變時(shí)才會(huì)觸發(fā)重新計(jì)算。8TY28資訊網(wǎng)——每日最新資訊28at.com

適用于異步操作或復(fù)雜邏輯。8TY28資訊網(wǎng)——每日最新資訊28at.com

適用于簡單計(jì)算。8TY28資訊網(wǎng)——每日最新資訊28at.com

不可以在HTML模板中使用8TY28資訊網(wǎng)——每日最新資訊28at.com

可以在HTML模板中使用8TY28資訊網(wǎng)——每日最新資訊28at.com

沒有返回值8TY28資訊網(wǎng)——每日最新資訊28at.com

有返回值/getter8TY28資訊網(wǎng)——每日最新資訊28at.com

可以修改data中的數(shù)據(jù)8TY28資訊網(wǎng)——每日最新資訊28at.com

也可以使用setters 修改 data 中的數(shù)據(jù)8TY28資訊網(wǎng)——每日最新資訊28at.com

總之,如果你需要在數(shù)據(jù)變化時(shí)執(zhí)行異步操作或復(fù)雜邏輯,使用watch是更好的選擇;如果你需要在數(shù)據(jù)變化時(shí)計(jì)算出一個(gè)新值,使用computed是更好的選擇。8TY28資訊網(wǎng)——每日最新資訊28at.com

關(guān)于watch的性能

watch的性能取決于你的代碼實(shí)現(xiàn)方式和監(jiān)聽的數(shù)據(jù)量。8TY28資訊網(wǎng)——每日最新資訊28at.com

  • 監(jiān)聽的數(shù)據(jù)量:如果你監(jiān)聽了大量的數(shù)據(jù),那么 watch 的性能可能會(huì)受到影響。
  • 代碼實(shí)現(xiàn):如果你在 watch 回調(diào)函數(shù)中執(zhí)行了復(fù)雜的邏輯或異步操作,那么 watch 的性能可能會(huì)受到影響。
  • 如果你只是需要在數(shù)據(jù)變化時(shí)執(zhí)行一些簡單的操作,那么 watch 的性能應(yīng)該是可以接受的。

所以,在使用watch時(shí),應(yīng)該注意監(jiān)聽的數(shù)據(jù)量,并且在watch回調(diào)函數(shù)中盡量少執(zhí)行復(fù)雜的邏輯.總之,watch監(jiān)聽數(shù)據(jù)更新并執(zhí)行回調(diào)函數(shù),性能會(huì)受到監(jiān)聽數(shù)據(jù)量和回調(diào)函數(shù)實(shí)現(xiàn)方式的影響,如果有性能問題,應(yīng)該優(yōu)化監(jiān)聽的數(shù)據(jù)量和回調(diào)函數(shù)的實(shí)現(xiàn)方式.8TY28資訊網(wǎng)——每日最新資訊28at.com

結(jié)束

今天的文章就介紹到這里,關(guān)于 watch 的用法你學(xué)會(huì)了,希望今天的文章能幫助到你,感謝你的閱讀。8TY28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-45498-0.htmlVue3 學(xué)習(xí)筆記,如何使用 Watch 監(jiān)聽數(shù)據(jù)變化

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: Node在項(xiàng)目中應(yīng)用案例之給幾百個(gè)下拉框統(tǒng)一加Filterable實(shí)現(xiàn)可搜索

下一篇: 你認(rèn)識(shí)Class、Dex、Arsc文件結(jié)構(gòu)嗎?

標(biāo)簽:
  • 熱門焦點(diǎn)
Top 主站蜘蛛池模板: 岚皋县| 禄劝| 英德市| 辰溪县| 白城市| 正蓝旗| 汽车| 和硕县| 高碑店市| 兴义市| 常州市| 尼勒克县| 乐山市| 平泉县| 林甸县| 钟祥市| 阳曲县| 资源县| 龙口市| 扶风县| 安庆市| 永昌县| 东乡县| 惠来县| 山阴县| 芮城县| 延安市| 夏河县| 隆德县| 邻水| 宿迁市| 嘉禾县| 麻栗坡县| 嘉黎县| 双桥区| 平阳县| 中西区| 焦作市| 密云县| 美姑县| 黑龙江省|