Vue實現雙向資料繫結的新姿勢
阿新 • • 發佈:2018-12-09
在Vue中實現資料繫結還是相當靈活的,可以通過屬性和指令兩種方式來實現
先來看看第一種方式使用ref屬性來來實現雙向資料繫結
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>雙向資料繫結</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <style type="text/css"> .box{ width: 400px; height: 400px; margin: 200 auto; text-align: center; line-height: 400px; background-color: #eee; } </style> </head> <body> <div id="app"> <h1>使用ref屬性實現資料繫結</h1> <lable>姓名:</lable> <!--只有按下enter鍵,才會輸出內容...--> <input ref="name" type="text" name="" id="" value="" v-on:keyup.enter = "username()"/> <span>{{name}}</span> <lable>年齡:</lable> <!--按下alt+enter鍵,才會輸出內容...--> <input ref="age" type="text" name="" id="" value="" v-on:keyup.alt.enter = "userage()"/> {{age}} </div> <script type="text/javascript"> new Vue({ el:'#app', data:{ name:"", age:"" }, methods:{ username: function(){ console.log("username...."); this.name = this.$refs.name.value; }, userage: function(){ console.log("userage..."); this.age = this.$refs.age.value; } } }) </script> </body> </html>
接下來再看看使用v-model指令實現雙向資料繫結,這中方式和angular的ng-model指令實現資料繫結如出一轍。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>雙向資料繫結</title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <style type="text/css"> .box{ width: 400px; height: 400px; margin: 200 auto; text-align: center; line-height: 400px; background-color: #eee; } </style> </head> <body> <div id="app"> <h1>使用v-model實現資料繫結</h1> <lable>姓名:</lable> <!--只有按下enter鍵,才會輸出內容...--> <input ref="name" type="text" name="" id="" value="" v-model = "name"/> <span>{{name}}</span> <lable>年齡:</lable> <!--按下alt+enter鍵,才會輸出內容...--> <input ref="age" type="text" name="" id="" value="" v-model ="age"/> {{age}} </div> <script type="text/javascript"> new Vue({ el:'#app', data:{ name:"", age:"" }, methods:{ } }) </script> </body> </html>