Vue.js 踩坑记 (五)

这篇体验一下VUE的双向绑定

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <div id="app">
        <input type="text" v-model="CurrentTime" placeholder="当前时刻">
        <h1>当前时刻{{ CurrentTime }}</h1>
    </div>
    <script>
    var app = new Vue({
        el:'#app',
        data:{
            CurrentTime: new Date()
        },
        mounted:function(){
            var _this = this;
            this.timer = setInterval(function(){
                _this.CurrentTime = new Date();
            },1000);
        },
        beforeDestroy:function(){
            if(this.timer){
                clearInterval(this.timer);
            }
        }
    });
    </script>
</body>
</html>


{{ }} 是所谓的文本插值的方法,目的是显示双向绑定的数据

mounted 表示el挂载到实例上调用的事件

beforeDestory 是实例销毁以前调用

在上例中,在mounted事件中创建了一个定时器,每隔一秒就把当前时间写入文本框中,由于双向绑定的原因,H1标签的文本也会跟着变化,和文本框的文本保持一致。在beforeDestory事件里在Vue实例销毁前则会清除定时器

猜你喜欢

转载自blog.csdn.net/lee576/article/details/80179826
今日推荐