1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport"
6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>07侦听器watch使用</title>
9 <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.40/vue.global.prod.js"></script>
10 </head>
11 <body>
12
13 <div id = "app">
14 <!--计算属性-->
15 <button @click="desc()">减少</button>{{num}}<button @click="add()">增加</button>
16 <!--侦听器-->
17 <div style="background-color: red;color: white" v-if="error">提示: {{error}}</div>
18 </div>
19 <script>
20 let app = Vue.createApp({
21 data() {
22 return {
23 num: 1,
24 error: '',
25 };
26 },
27 // 侦听器用来检测一个数据的改变并做相应的业务操作
28 watch: {
29 // 侦听num响应式数据
30 num(newValue,oldValue){
31 console.log(newValue,oldValue);
32 this.error = newValue === 0 ? '不能小于0' : newValue === 10 ? '不能超过10' : ''
33 },
34 },
35 methods:{
36 add(){
37 // this表示当前的组件(当前是根组件,即下面的vm)
38 if (this.num < 10) this.num++;
39 },
40 desc() {
41 if (this.num > 0) this.num--;
42 },
43 },
44 });
45
46 let vm = app.mount('#app');
47 </script>
48 </body>
49