1.vue的基本语法
<div id="vue_det"> <h1>site : {{site}}</h1> <h1>url : {{url}}</h1> <h1>{{details()}}</h1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "你好", url: "www.nihao.com", alexa: "10000" }, methods: { details: function() { return this.site + "梦想!"; } } }) </script>可以看到在 Vue 构造器中有一个el 参数,它是 DOM 元素中的 id。在上面实例中 id 为 vue_det,在 div 元素中:
<div id = "vue_det"></div>
这意味着我们接下来的改动全部在以上指定的 div 内,div 外部不受影响。 接下来我们看看如何定义数据对象。data 用于定义属性,实例中有三个属性分别为:site、url、alexa。 methods 用于定义的函数,可以通过 return 来返回函数值。 {{ }} 用于输出对象属性和函数返回值。
2.HTML 属性中的值应使用 v-bind 指令。
以下实例判断 class1 的值,如果为 true 使用 class1 类的样式,否则不使用该类
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例</title> </head> <style> .class1{ background: #444; color: #eee; } </style> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="app"> <label for="r1">修改颜色</label><input type="checkbox" v-model="use" id="r1"> <br><br> <div v-bind:class="{'class1': use}"> v-bind:class 指令 </div> </div> <script> new Vue({ el: '#app', data:{ use: false } }); </script> </body>v-modle双重绑定 在 input 输入框中我们可以使用 v-model 指令来实现双向数据绑定:
v-if 判断 v-html用于输出 html 代码 v-on 指令,它用于监听 DOM 事件
<div id="app"> <div v-html="message"></div> </div> <script> new Vue({ el: '#app', data: { message: '<h1>测试案例</h1>' } }) </script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例</title> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> </head> <body> <div id="app"> <p>{{ message }}</p> <button v-on:click="reverseMessage">反转字符串</button> <input type="checkbox" v-model="use" id="r1">测试 //双重绑定,相互影响 <p v-if="use" >现在你看到我了</p> </div> <script> new Vue({ el: '#app', data: { message: 'Runoob!', use:false }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } }) </script> </body> </html>vue为bind和on提供了两种缩写 v-href:url="ddd" 缩写为 :url="ddd",另一种@bind