Vue.js 快速入門
什么是Vue.js
vue是法語中視圖的意思,Vue.js是一個輕巧、高性能、可組件化的MVVM庫,同時擁有非常容易上手的API。作者是尤雨溪,寫下這篇文章時vue.js版本為1.0.7
準備
我推薦使用sublime text作為編輯器,關于這個編輯器可以看我這篇文章。在package control中安裝
-
Vuejs Snippets
</li> -
Vue Syntax Highlight
</li> </ul>推薦使用npm管理,新建兩個文件app.html,app.js,為了美觀使用bootstrap,我們的頁面模板看起來是這樣:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" type="text/css" > </head> <body> <div class="container"> <div class="col-md-6 col-md-offset-3"> <h1>Vue demo</h1> <div id="app"> ....... </div> </div> </div> </body> </html>
安裝
使用npm安裝:
npm install vue
當然你也可以在github上clone最新的版本并作為單文件引入,或者使用CDN:
http://cdn.jsdelivr.net/vue/1.0.7/vue.min.js http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.7/vue.min.js
HelloWorld
動手寫第一個Vue.js 應用吧。app.html:
<div id="app"> <div>{{message}}</div> <input type="text" v-model="message"> </div>
app.js:
new Vue({ el:'#app', data: { message:'hello vue.js.' } });
創建Vue實例
在使用Vue.js之前,我們需要先像這樣實例化一個Vue對象:
new Vue({ el:'#app' });
雙向數據綁定
就像HelloWorld展示的那樣,app.html是view層,app.js是model層,通過vue.js(使用v-model這個指令)完成中間的底層邏輯,實現綁定的效果。改變其中的任何一層,另外一層都會改變。
插值
相信你也注意到了,通過{{value}}的形式就能取到value的值,并與value進行綁定。HelloWorld中改變input中的值時相應也改變了app.js中的message,從而{{message}}也得到改變。上面的代碼改為這樣:
{{*message}}
則message不會隨著數據的改變而更新。同時還支持一些簡單的表達式:
{{message + 'vue is awesome'}} {{ message.split('').reverse().join('') }}
常用的指令
v-model
v-model可用于一些表單元素,常見的input,checkbox,radio,select:
<select v-model="selected" multiple> <option selected>A</option> <option>B</option> <option>C</option> </select> <br> <span>Selected: {{ selected | json }}</span>
v-for
列表渲染在實際開發中非常常見,vue.js使用v-for這個指令就能完成,v-for取代了1.0以前版本中的v-repeat。在app.js中準備一些數據:
new Vue({ el: '#app', data: { book: { id: 0, author: '', name: '', price: '' }, books: [{ id: 1, author: '曹雪芹', name: '紅樓夢', price: 32.0 }, { id: 2, author: '施耐庵', name: '水滸傳', price: 30.0 }, { id: '3', author: '羅貫中', name: '三國演義', price: 24.0 }, { id: 4, author: '吳承恩', name: '西游記', price: 20.0 }] } })
在data里我們設置了兩個數據book和book[] books,在app.html中我們只要這樣就能獲取到數據了:
<tr v-for="book in books "> <td>{{book.id}}</td> <td>{{book.name}}</td> <td>{{book.author}}</td> <td>{{book.price}}</td> </tr>
如果你比較細心的話,在數據還未加載完時是會有閃爍的情況出現,解決方法也很簡單,使用v-cloak,然后定義css:
[v-cloak] { display: none }
v-on
vue.js通過v-on完成事件處理與綁定,比如為一個button綁定click事件,我們就可以這么寫:
<button v-on:click="doSomething">doSomething</button>
也可以縮寫:
<button @click="doSomething">doSomething</button>
我們需要為v-on傳入事件參數,然后在vue的實例中聲明doSomething這個方法就可以調用了:
new Vue({ el: '#app', methods: { doSomething: function () { /...../ } } })
接著上面書的例子,我們用v-model綁定form:
<div id="add-book"> <legend>添加書籍</legend> <div class="form-group"> <label for="">書名</label> <input type="text" class="form-control" v-model="book.name"> </div> <div class="form-group"> <label for="">作者</label> <input type="text" class="form-control" v-model="book.author"> </div> <div class="form-group"> <label for="">價格</label> <input type="text" class="form-control" v-model="book.price"> </div> <button class="btn btn-primary btn-block" v-on:click="addBook()">添加</button> </div>
在app.js中增加我們的addBook方法:
methods: { addBook: function() { //計算書的id this.book.id = this.books.length + 1; this.books.push(this.book); //將input中的數據重置 this.book = ''; } }
我們再健全一下功能,增加一個刪除按鈕:
<button type="button" class="btn btn-danger" @click="delBook(book)">刪除</button>
delBook方法:
delBook:function(book){ this.books.$remove(book); }
vue.js為數組擴展了$remove方法,查找并刪除我們作為參數傳遞過去的book。
v-if/v-else/v-show
顧名思義,v-if用于條件判斷,和v-else是一對。用法也很簡單,下面的代碼是將id為偶數的操作按鈕換個樣式:
<template v-if="book.id%2==0"> <td class="text-right"> ...... <button type="button" class="btn btn-success" @click="delBook(book)">刪除</button> ..... </td> </template> <template v-else> ..... <td class="text-right"> <button type="button" class="btn btn-danger" @click="delBook(book)">刪除</button> </td> .... </template>
這里用到了<template>標簽,用于包含多個元素,當元素只有一個時,直接在元素上用v-if即可:
<h1 v-if="ok">Yes</h1> <h1 v-else>No</h1>
v-show作用與v-if類似,不同的是v-show的元素會始終渲染并保持在 DOM 中,且v-show不支持<template>標簽。
過濾器
與Linux中的管道類似,vue.js也使用的是|:
{{message | uppercase}}
這樣就能輸出message的大寫了,過濾器也能串聯在一起使用:
{{message | reverse | uppercase}}
這里reverse并不是內建的過濾器,我們可以用Vue.filter自定義:
Vue.filter('reverse', function (value) { return value.split('').reverse().join('') })
過濾器支持接收參數,比較常用的是orderBy [param]和filterBy [param],現在我們為表格增加自定義排序的功能,為表頭綁定click事件:
<th class="text-right" @click="sortBy('id')">序號</th> <th class="text-right" @click="sortBy('name')">書名</th> <th class="text-right" @click="sortBy('author')">作者</th> <th class="text-right" @click="sortBy('price')">價格</th>
想sortBy傳遞列的參數,定義sortBy和data:
data: { sortparam: '' }, methods:{ sortBy: function(sortparam) { this.sortparam = sortparam; } }
添加過濾器:
<tr v-for="book in books | orderBy sortparam">
計算屬性
計算屬性可以幫助我們完成一些復雜的邏輯計算,比如我們需要添加一個書的總價,在vue實例中添加computed:
new Vue({ /.../ computed: { sum: function() { var result = 0; for (var i = 0; i < this.books.length; i++) { result = Number(this.books[i].price) + result; }; return result; } }, /.../ })
在app.html中使用插值表達式:
{{sum}}
vue-resource
vue-resource作為vue插件的形式存在,通過 XMLHttpRequest 或 JSONP 發起請求并處理響應。在開發中也非常常見,現在我們用vue-resource來請求books:
引入
和vue類似:
npm install vue-resource --save
如果你的項目遵循CommonJS: var Vue = require('vue'); Vue.use(require('vue-resource'));</pre>
也可以直接引入單文件或者CDN。
get
在vue中新增ready對象,當頁面加載完成時就去請求:
new Vue({ el: '#app', ready: function() { this.$http.get('book.json', function(data) { this.$set('books', data); }).error(function(data, status, request) { console.log('fail' + status + "," + request); }) }, data: { .... books:'' }, .....
為了演示,這里將json格式的數據保存在book.json中,這段數據你可以直接使用JSON.stringify()得到:
[{"id":1,"author":"曹雪芹","name":"紅樓夢","price":32},{"id":2,"author":"施耐庵","name":"水滸傳","price":30},{"id":"3","author":"羅貫中","name":"三國演義","price":24},{"id":4,"author":"吳承恩","name":"西游記","price":20}]
接下來你需要將app.html中運行在一個服務器中,否則由于瀏覽器安全的限制,是無法直接讀取的,如果你嫌麻煩可以用這個參數啟動chrome。
.\chrome.exe --allow-file-access-from-files
如果你使用了npm,想要啟動一個服務器就太簡單了:
npm install http-server -g //在當前目錄 http-server //然后訪問localhost:8080/app.html
post
post的語法也很簡單:
this.$http.post(url,postdata,function callback)
在使用的時候遇到一個小坑,這個$http請求和jquery的ajax還是有點區別,這里的post的data默認不是以form data的形式,而是request payload。解決起來也很簡單:在vue實例中添加headers字段:
http: { headers: {'Content-Type': 'application/x-www-form-urlencoded'} }
后來翻了下vue-resource的源碼,發現有更加簡單的做法:
Vue.http.options.emulateJSON = true;
這里只簡單介紹下,詳細的文檔請大家移步 這里 吧。
vue.js目前還有眾多的插件,詳情看 這里 。
總結
這里簡單介紹了下vue.js的基本用法,但只僅僅介紹了一小部分作為庫使用的內容,想了解更多vue.js的內容,還是多多關注vue.js的 github主頁 ,所用的例子我也分享了,可以在 這里 查看并運行結果。
更多