Vue3中使用监听器的具体实践
作者:Python私教
监听器是Vue3中非常好用的一个特性,用于监听某个响应式变量的变化,本文就来介绍一下Vue3中使用监听器的具体实践,具有一定的参考价值,感兴趣的可以了解一下
概述
监听器是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/

完整代码
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)
// 监听器监听
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/
到此这篇关于Vue3中使用监听器的具体实践的文章就介绍到这了,更多相关Vue3 监听器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
