监听器是Vue3中非常好用的一个特性,用于监听某个响应式变量的变化。
监听器支持在被监听的响应式变量发生改变的时候,获取修改之前的值和修改之后的值,并触发一个回调函数。
比如,我们拿熟悉的计数器案例来说,正常逻辑下计数器是不能够低于0的,那么我们监听到计数器小于0的时候,就弹出提示。
我们创建src/components/Demo27.vue,代码如下:
<script setup>
import {computed, ref, watch} from "vue";
const count = ref(0)
// 监听器监听
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>
然后,我们浏览器访问:http://localhost:5173/
{
"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"
}
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<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>
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<script setup>
import Demo from "./components/Demo27.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
<script setup>
import {computed, ref, watch} from "vue";
const count = ref(0)
// 监听器监听
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/