Vue3中使用監(jiān)聽器的具體實踐
概述
監(jiān)聽器是Vue3中非常好用的一個特性,用于監(jiān)聽某個響應(yīng)式變量的變化。
監(jiān)聽器支持在被監(jiān)聽的響應(yīng)式變量發(fā)生改變的時候,獲取修改之前的值和修改之后的值,并觸發(fā)一個回調(diào)函數(shù)。
比如,我們拿熟悉的計數(shù)器案例來說,正常邏輯下計數(shù)器是不能夠低于0的,那么我們監(jiān)聽到計數(shù)器小于0的時候,就彈出提示。
基本用法
我們創(chuàng)建src/components/Demo27.vue,代碼如下:
<script setup> import {computed, ref, watch} from "vue"; const count = ref(0) // 監(jiān)聽器監(jiān)聽 watch(count, function (value, oldValue) { if (value < 0) { alert(`無法將count從${oldValue}改為${value},因為修改后count小于0了`) } }) </script> <template> <div> <h3>{{ count }}</h3> <div> <button @click="count+=10">增加</button> <button @click="count-=10">減少</button> </div> </div> </template>
接著,我們修改src/App.vue:
<script setup> import Demo from "./components/Demo27.vue" </script> <template> <h1>歡迎跟著Python私教一起學習Vue3入門課程</h1> <hr> <Demo/> </template>
然后,我們?yōu)g覽器訪問:http://localhost:5173/
完整代碼
package.json
{ "name": "hello", "private": true, "version": "0.1.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build" }, "dependencies": { "vue": "^3.3.8" }, "devDependencies": { "@vitejs/plugin-vue": "^4.5.0", "vite": "^5.0.0" } }
vite.config.js
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], })
index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" rel="external nofollow" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + Vue</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>
src/main.js
import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app')
src/App.vue
<script setup> import Demo from "./components/Demo27.vue" </script> <template> <h1>歡迎跟著Python私教一起學習Vue3入門課程</h1> <hr> <Demo/> </template>
src/components/Demo27.vue
<script setup> import {computed, ref, watch} from "vue"; const count = ref(0) // 監(jiān)聽器監(jiān)聽 watch(count, function (value, oldValue) { if (value < 0) { alert(`無法將count從${oldValue}改為${value},因為修改后count小于0了`) } }) </script> <template> <div> <h3>{{ count }}</h3> <div> <button @click="count+=10">增加</button> <button @click="count-=10">減少</button> </div> </div> </template>
啟動方式
yarn yarn dev
瀏覽器訪問:http://localhost:5173/
到此這篇關(guān)于Vue3中使用監(jiān)聽器的具體實踐的文章就介紹到這了,更多相關(guān)Vue3 監(jiān)聽器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vuex數(shù)據(jù)傳輸?shù)膬煞N方式及this.$store undefined的解決辦法
這篇文章主要介紹了vuex數(shù)據(jù)傳輸?shù)膬煞N方式 及 this.$store undefined的解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決
這篇文章主要介紹了moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05