一、定义
Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。
Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。
<!-- 开发环境版本,包含了用帮助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- 生产环境版本,优化了尺寸和速度 --> <script src="https://cdn.jsdelivr.net/npm/vue"></script>
模板语言
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> {{ message }} </div> <script> var app = new Vue({ el: '#app', // 操作标签 data: { message: 'Hello Vue!' // 操作内容 } }) </script> </body> </html>
绑定元素特性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <span v-bind:title="message">点我点我</span> </div> <script> var app = new Vue({ el: '#app', // 操作标签 data: { message: '页面加载于 '+ new Date().toLocaleString() } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> <script> var app = new Vue({ el: '#app', // 操作标签 data: { todos:[ {text:'python'}, {text:'java'}, {text:'厉害了'} ] } }) </script> </body> </html>
监听事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <p>{{ message }}</p> <button v-on:click="reverseMessage">逆转消息</button> </div> <script> var app = new Vue({ el: '#app', data: { message: 'hello vue.js nice to meet you!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } }) </script> </body> </html>
Vue 还提供了 v-model
指令,它能轻松实现表单输入和应用状态之间的双向绑定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <p>{{ message }}</p> <input type="text" v-model="message"> </div> <script> var app = new Vue({ el: '#app', data: { message: 'hello vue.js nice to meet you!' } }) </script> </body> </html>
详细中文教程:传送门