10_watch.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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>{{obj.c.x}}</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. obj:{
  23. a:1,
  24. b:2,
  25. c:{
  26. x:100,
  27. y:200
  28. }
  29. }
  30. },
  31. methods:{
  32. change(){
  33. this.num++;
  34. // this.arr.push(5);
  35. // this.arr[1] = "hello";
  36. // this.arr = ["a","b","c"];
  37. // this.$set(this.arr[2],0,"hello");
  38. this.obj.c.x = 1000;
  39. }
  40. },
  41. watch:{
  42. // 监听data中某个属性变化 监听谁就以谁为方法名
  43. // 只要num变化了,就会调用num方法
  44. // 方法中会有两个参数,分别是新值和旧值
  45. num(newVal,oldVal){
  46. console.log(newVal,oldVal);
  47. },
  48. // watch 默认只能监听基本数据类型
  49. // 如果要监听数组或对象变化,需要设置deep:true
  50. // arr:{
  51. // // 监听数组或对象变化时,会调用handler方法
  52. // handler(){
  53. // console.log("arr变化了");
  54. // },
  55. // // 开启deep监听后,会监听数组或对象中的所有属性
  56. // deep:true
  57. // }
  58. // arr(){
  59. // console.log("arr变化了");
  60. // }
  61. // obj(newVal,oldVal){
  62. // console.log(newVal,oldVal);
  63. // }
  64. obj:{
  65. handler(){
  66. console.log("obj变化了");
  67. },
  68. deep:true
  69. }
  70. }
  71. })
  72. </script>
  73. </body>
  74. </html>