美文网首页
(四)Vue中的watch方法

(四)Vue中的watch方法

作者: 我拥抱着我的未来 | 来源:发表于2018-02-15 17:32 被阅读0次

本节知识点

  • watch方法动态监听变化
app.$watch(" xxx",function(newVal,oldVal){})

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="js/vue.js"></script>
    <title>Watch option</title>
</head>
<body>
<h1>Watch option</h1>
<hr>
<div id="app">
    <p>今日温度:{{temperature}}°C</p>
    <p>穿衣建议:{{this.suggestion}}</p>
    <p>
        <button @click="add">添加温度</button>
        <button @click="reduce">减少温度</button>

    </p>
</div>

<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,oldVal){
        //         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){
        if(newVal>=26){
            this.suggestion=suggestion[0];
        }else if(newVal<26 && newVal >=0)
        {
            this.suggestion=suggestion[1];
        }else{
            this.suggestion=suggestion[2];
        }

    })

</script>
</body>
</html>

相关文章

网友评论

      本文标题:(四)Vue中的watch方法

      本文链接:https://www.haomeiwen.com/subject/vurutftx.html