Watch 选项 监控数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.set全局操作</title>
    <meta name="flexible" content="initial-dpr=2,maximum-dpr=3" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta content="yes" name="apple-touch-fullscreen">
     <meta content="telephone=no,email=no" name="format-detection">
    <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
    <script src="../assets/js/flexible_css.js"></script>
    <script src="../assets/js/flexible.js"></script>
    <script src="../assets/js/vue.js"></script>
</head>
<body>
    <div id="app">
        <p>今日温度:{{temperature}}°C</p>
        <p>穿衣建议:{{suggestion}}</p>
        <p>
            <button @click="add">添加温度</button>
            <button @click="reduce">减少温度</button>
        </p>
</div>
</body>
<script type="text/javascript">
    var suggestion=['T恤短袖','夹克长裙','棉衣羽绒服'];
    
        var app=new Vue({
            el:'#app',
            data:{
                temperature:14,
                suggestion:'夹克长裙'
            },
            methods:{
                add:function(){
                    this.temperature+=5;
                },
                reduce:function(){
                    this.temperature-=5;
                }
            },
            // watch:{  //  看守,监视    //第一种在构造器里面
            //     temperature:function(newVal){
            //         if(newVal>=26){
            //             this.suggestion=suggestion[0];
            //         }else if(newVal<26 && newVal >=0)
            //         {
            //             this.suggestion=suggestion[1];
            //         }else{
            //             this.suggestion=suggestion[2];
            //         }
            //     }
            // }

        })

     app.$watch('temperature',function(newVal,oldVal){  ///第二种在构造器外面    实例属性写watch监控 
        if(newVal>=26){
            this.suggestion=suggestion[0];
        }else if(newVal<26 && newVal >=0)
        {
            this.suggestion=suggestion[1];
        }else{
            this.suggestion=suggestion[2];
        }
    //   监控属性有两种写法  第一种在构造器里面,第二种在构造器外面
    })
</script> 
</html>

 

posted @ 2018-02-28 17:43  Jinsuo  阅读(161)  评论(0编辑  收藏  举报