Vue之变量、数据绑定、事件绑定使用举例
vue1.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-html="http://www.w3.org/1999/xhtml" 3 xmlns:v-on="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Vue Demo</title> 7 <!--自选版本--> 8 <!--<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>--> 9 <!-- 开发环境版本,包含了有帮助的命令行警告 --> 10 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 11 <!-- 生产环境版本,优化了尺寸和速度 --> 12 <!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>--> 13 <link href="style.css" rel="stylesheet"> 14 </head> 15 <body> 16 <div id="app"> 17 <!--变量和方法调用--> 18 <h1>{{ greet("night") }}</h1> 19 <p>{{ message }}</p> 20 <hr> 21 22 <p> 23 <!--数据绑定--> 24 <a v-bind:href="website">百度</a> 25 </p> 26 <p v-html="websiteTag"></p> 27 <hr> 28 29 <div> 30 <div> 31 <!--事件绑定--> 32 <button v-on:click="add(1)">单击加一岁</button> 33 <button @click="sub(1)">单击减一岁</button> 34 <!--双击操作--> 35 <button v-on:dblclick="add(10)">双击加十岁</button> 36 <button @dblclick="sub(10)">双击减十岁</button> 37 </div> 38 <p>我的年龄是{{age}}</p> 39 40 <hr> 41 <div id="canvas" v-on:mousemove="updateXY"> 42 {{x}} ,{{y}} 43 </div> 44 </div> 45 46 47 </div> 48 <script src="app.js"></script> 49 50 <hr> 51 <div id="app-2"> 52 <span v-bind:title="message"> 53 鼠标悬停几秒钟查看此处动态绑定的提示信息! 54 </span> 55 </div> 56 <script src="app2.js"></script> 57 58 </body> 59 </html>
app.js
1 var app = new Vue({ 2 el: '#app', 3 data: { 4 name: "Tom", 5 message: 'Hello Vue!', 6 website: "http://www.baidu.com", 7 websiteTag: "<a href='http://www.baidu.com'>百度Tag</a>", 8 age: 30, 9 x: 0, 10 y: 0, 11 12 }, 13 methods: { 14 greet: function (time) { 15 return 'Good ' + time + '!' + this.name; 16 }, 17 18 // 事件绑定 19 add: function (n) { 20 this.age += n; 21 }, 22 sub: function (n) { 23 this.age -= n; 24 }, 25 26 updateXY: function (event) { 27 // console.log(event); 28 this.x = event.offsetX; 29 this.y = event.offsetY; 30 } 31 }, 32 })
app2.js
1 var app2 = new Vue({ 2 el: '#app-2', 3 data: { 4 message: '页面加载于 ' + new Date().toLocaleString() 5 } 6 })
style.css
1 #canvas { 2 width: 600px; 3 padding: 200px 20px; 4 text-align: center; 5 border: 1px solid; 6 }
截图: