10_watch.html 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <div id="app">
  10. <div>{{num}}</div>
  11. <div>{{arr}}</div>
  12. <input type="text" v-model.number="num">
  13. <button @click="change">按钮</button>
  14. </div>
  15. <script src="./js/vue.js"></script>
  16. <script>
  17. new Vue({
  18. el:"#app",
  19. data:{
  20. num:0,
  21. arr:[1,2,3,4]
  22. },
  23. methods:{
  24. change(){
  25. this.num++;
  26. // this.arr.push(5);
  27. // this.arr[1] = "hello";
  28. // this.arr = ["a","b","c"];
  29. }
  30. },
  31. watch:{
  32. // 监听data中某个属性变化 监听谁就以谁为方法名
  33. // 只要num变化了,就会调用num方法
  34. // 方法中会有两个参数,分别是新值和旧值
  35. num(newVal,oldVal){
  36. console.log(newVal,oldVal);
  37. },
  38. // watch 默认只能监听基本数据类型
  39. // 如果要监听数组或对象变化,需要设置deep:true
  40. // arr:{
  41. // // 监听数组或对象变化时,会调用handler方法
  42. // handler(){
  43. // console.log("arr变化了");
  44. // },
  45. // // 开启deep监听后,会监听数组或对象中的所有属性
  46. // deep:true
  47. // }
  48. // arr(){
  49. // console.log("arr变化了");
  50. // }
  51. }
  52. })
  53. </script>
  54. </body>
  55. </html>