Vue.js 快速入門

什麼是Vue.js

vue是法語中視圖的意思,Vue.js是一個輕巧、高性能、可組件化的MVVM庫,同時擁有很是容易上手的API。做者是尤雨溪,寫下這篇文章時vue.js版本爲1.0.7css

準備

我推薦使用sublime text做爲編輯器,關於這個編輯器能夠看我這篇文章。在package control中安裝html

  • Vuejs Snippetsvue

  • Vue Syntax Highlightjquery

推薦使用npm管理,新建兩個文件app.html,app.js,爲了美觀使用bootstrap,咱們的頁面模板看起來是這樣:git

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.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安裝:github

npm install vue

固然你也能夠在github上clone最新的版本並做爲單文件引入,或者使用CDN:ajax

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:chrome

<div id="app">
    <div>{{message}}</div>
    <input type="text" v-model="message">
</div>

app.js:npm

new Vue({
    el:'#app',
    data: {
        message:'hello vue.js.'
    }
});

建立Vue實例

在使用Vue.js以前,咱們須要先像這樣實例化一個Vue對象:json

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'));

也能夠直接引入單文件或者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主頁,所用的例子我也分享了,能夠在這裏查看並運行結果。

更多

相關文章
相關標籤/搜索