2.天气案例_监视属性.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>天气案例_监视属性</title>
  8. <!-- 引入vue -->
  9. <script type="text/javascript" src="../js/vue.js"></script>
  10. </head>
  11. <body>
  12. <!--
  13. 监视属性watch:
  14. 1、当被监视的属性变化时,回调函数(本例中的handler)自动调用,进行相关操作
  15. 2、监视的属性必须存在,才能进行监视!!
  16. 3、监事会的两种写法:
  17. (1)、new Vue时传入watch配置
  18. (2)、通过vm.$watch监视
  19. -->
  20. <!-- 准备好一个容器 -->
  21. <div id="root">
  22. <h2>今天天气很{{info}}</h2>
  23. <button @click="changeWeathers">切换天气</button>
  24. </div>
  25. </body>
  26. <script type="text/javascript">
  27. Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示
  28. const vm = new Vue({
  29. el:'#root',
  30. data:{
  31. isHot:true
  32. },
  33. computed:{
  34. info(){
  35. return this.isHot ? '炎热' : '凉爽'
  36. }
  37. },
  38. methods: {
  39. changeWeathers(){
  40. this.isHot = !this.isHot
  41. }
  42. },
  43. // watch:{
  44. // isHot:{
  45. // immediate:true, //初始化时让handler调用一下
  46. // // handler什么时候调用?当isHot发生改变时。
  47. // handler(newValue,oldValue){
  48. // console.log('isHot被修改了',newValue,oldValue)
  49. // }
  50. // },
  51. // // 可以监视计算属性
  52. // // info:{
  53. // // immediate:true, //初始化时让handler调用一下
  54. // // // handler什么时候调用?当isHot发生改变时。
  55. // // handler(newValue,oldValue){
  56. // // console.log('info',newValue,oldValue)
  57. // // }
  58. // // }
  59. // }
  60. })
  61. vm.$watch('isHot',{
  62. immediate:true, //初始化时让handler调用一下
  63. // handler什么时候调用?当isHot发生改变时。
  64. handler(newValue,oldValue){
  65. console.log('isHot被修改了',newValue,oldValue)
  66. }
  67. })
  68. </script>
  69. </html>