Vue中怎么实现属性绑定和双向数据绑定

这篇文章给大家介绍Vue中怎么实现属性绑定和双向数据绑定,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

使用实例中的data可进行数据绑定

使用v-model:进行双向数据绑定

监听事件:watch

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Vue学习</title>
        <script src="js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            姓:<input v-model="firstName" />
            名:<input v-model="lastName" />
            <div>{{fullName}}</div>
            <div>{{count}}</div>
        </div>
    </body>
    <script>
        new Vue({
            el:"#root",
            data:{
                firstName:'',
                lastName:'',
                count:0
            },
            computed:{
                fullName:function(){
                    return this.firstName + ' '+ this.lastName
                }
            },
            watch:{
                fullName:function(){
                    this.count++
                }
            }
        })
    </script>
</html>

当full Name改变时,watch会监听,使count的数值+1

count的初始值为0

Vue中怎么实现属性绑定和双向数据绑定

当改变firstName时,count+1

Vue中怎么实现属性绑定和双向数据绑定

改变lastName时count+1

Vue中怎么实现属性绑定和双向数据绑定

Vue中怎么实现属性绑定和双向数据绑定

同时也会看到fullName会跟随输入内容的变化而变化,这就实现了双向数据绑定。

关于Vue中怎么实现属性绑定和双向数据绑定就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。