JavaScript的MVVM庫Vue.js入門學(xué)習(xí)筆記

字號:


    這篇文章主要介紹了JavaScript的MVVM庫Vue.js入門學(xué)習(xí)筆記,Vue.js是一個新興的js庫,主要用于實現(xiàn)響應(yīng)的數(shù)據(jù)綁定和組合的視圖組件,需要的朋友可以參考下
    一、v-bind 縮寫
    <!-- 完整語法 -->
    <a v-bind:href="url"></a>
    <!-- 縮寫 -->
    <a :href="url"></a>
    <!-- 完整語法 -->
    <button v-bind:disabled="someDynamicCondition">Button</button>
    <!-- 縮寫 -->
    <button :disabled="someDynamicCondition">Button</button>
    二、v-on 縮寫
    <!-- 完整語法 -->
    <a v-on:click="doSomething"></a>
    <!-- 縮寫 -->
    <a @click="doSomething"></a>
    三、過濾器
    {{ message | capitalize }}
    四、條件渲染
    v-if
    <h1 v-if="ok">Yes</h1>
    <h1 v-else>No</h1>
    <div v-if="Math.random() > 0.5">
     Sorry
    </div>
    <div v-else>
     Not sorry
    </div>
    template-v-if
    <template v-if="ok">
     <h1>Title</h1>
     <p>Paragraph 1</p>
     <p>Paragraph 2</p>
    </template>
    v-show
    <h1 v-show="ok">Hello!</h1>
    五、列表渲染 for
    v-for
    <ul id="example-1">
     <li v-for="item in items">
     {{ item.message }}
     </li>
    </ul>
    var example1 = new Vue({
     el: '#example-1',
     data: {
     items: [
      { message: 'Foo' },
      { message: 'Bar' }
     ]
     }
    });
      
    <ul id="example-2">
     <li v-for="item in items">
     {{ parentMessage }} - {{ $index }} - {{ item.message }}
     </li>
    </ul>
    var example2 = new Vue({
     el: '#example-2',
     data: {
     parentMessage: 'Parent',
     items: [
      { message: 'Foo' },
      { message: 'Bar' }
     ]
     }
    });
    數(shù)組變動檢測
    Vue.js 包裝了被觀察數(shù)組的變異方法,故它們能觸發(fā)視圖更新。被包裝的方法有:push(), pop(), shift(), unshift(), splice(), sort(), reverse()
    example1.items.push({ message: 'Baz' });
    example1.items = example1.items.filter(function (item) {
     return item.message.match(/Foo/);
    }); 
    template-v-for
    <ul>
     <template v-for="item in items">
     <li>{{ item.msg }}</li>
     <li></li>
     </template>
    </ul> 
    對象 v-for
    <ul id="repeat-object">
     <li v-for="value in object">
     {{ $key }} : {{ value }}
     </li>
    </ul>
    new Vue({
     el: '#repeat-object',
     data: {
     object: {
      FirstName: 'John',
      LastName: 'Doe',
      Age: 30
     }
     }
    }); 
    值域 v-for
    <div>
     <span v-for="n in 10">{{ n }} </span>
    </div>
    六、方法與事件處理器
    方法處理器
    <div id="example">
     <button v-on:click="greet">Greet</button>
    </div>
    var vm = new Vue({
     el: '#example',
     data: {
     name: 'Vue.js'
     },
     // 在 `methods` 對象中定義方法
     methods: {
     greet: function (event) {
      // 方法內(nèi) `this` 指向 vm
      alert('Hello ' + this.name + '!')
      // `event` 是原生 DOM 事件
      alert(event.target.tagName)
     }
     }
    })
    // 也可以在 JavaScript 代碼中調(diào)用方法
    vm.greet(); // -> 'Hello Vue.js!'
    內(nèi)聯(lián)語句處理器
    <div id="example-2">
     <button v-on:click="say('hi')">Say Hi</button>
     <button v-on:click="say('what')">Say What</button>
    </div>
    new Vue({
     el: '#example-2',
     methods: {
     say: function (msg) {
      alert(msg)
     }
     }
    });
    有時也需要在內(nèi)聯(lián)語句處理器中訪問原生 DOM 事件??梢杂锰厥庾兞?$event 把它傳入方法
    <button v-on:click="say('hello!', $event)">Submit</button>
     methods: {
     say: function (msg, event) {
     // 現(xiàn)在我們可以訪問原生事件對象
     event.preventDefault()
     }
    };
    ## 事件修飾符
    <!-- 阻止單擊事件冒泡 -->
    <a v-on:click.stop="doThis"></a>
    <!-- 提交事件不再重載頁面 -->
    <form v-on:submit.prevent="onSubmit"></form>
    <!-- 修飾符可以串聯(lián) -->
    <a v-on:click.stop.prevent="doThat">
    <!-- 只有修飾符 -->
    <form v-on:submit.prevent></form>
    ## 按鍵修飾符
    <!-- 只有在 keyCode 是 13 時調(diào)用 vm.submit() -->
    <input v-on:keyup.13="submit">
    <!-- 同上 -->
    <input v-on:keyup.enter="submit">
    <!-- 縮寫語法 -->
    <input @keyup.enter="submit">
    全部的按鍵別名:enter,tab,delete,esc,space,up,down,left,right
    ## 其他實例
    new Vue({
     el: '#demo',
     data: {
     newLabel: '',
     stats: stats
     },
     methods: {
     add: function (e) {
      e.preventDefault()
      if (!this.newLabel) {
      return;
      }
      this.stats.push({
      label: this.newLabel,
      value: 100
      });
      this.newLabel = '';
     },
     remove: function (stat) {
      if (this.stats.length > 3) {
      this.stats.$remove(stat); // 注意這里的$remove
      } else {
      alert('Can\'t delete more!')
      }
     }
     }
    });
    七、過渡
    CSS 過渡
    <div v-if="show" transition="expand">hello</div>
    然后為 .expand-transition, .expand-enter 和 .expand-leave 添加 CSS 規(guī)則:
    /* 必需 */
    .expand-transition {
     transition: all .3s ease;
     height: 30px;
     padding: 10px;
     background-color: #eee;
     overflow: hidden;
    }
    /* .expand-enter 定義進(jìn)入的開始狀態(tài) */
    /* .expand-leave 定義離開的結(jié)束狀態(tài) */
    .expand-enter, .expand-leave {
     height: 0;
     padding: 0 10px;
     opacity: 0;
    }
    你可以在同一元素上通過動態(tài)綁定實現(xiàn)不同的過渡:
    <div v-if="show" :transition="transitionName">hello</div> 
    new Vue({
     el: '...',
     data: {
     show: false,
     transitionName: 'fade'
     }
    }
    另外,可以提供 JavaScript 鉤子:
    Vue.transition('expand', {
     beforeEnter: function (el) {
     el.textContent = 'beforeEnter'
     },
     enter: function (el) {
     el.textContent = 'enter'
     },
     afterEnter: function (el) {
     el.textContent = 'afterEnter'
     },
     enterCancelled: function (el) {
     // handle cancellation
     },
     beforeLeave: function (el) {
     el.textContent = 'beforeLeave'
     },
     leave: function (el) {
     el.textContent = 'leave'
     },
     afterLeave: function (el) {
     el.textContent = 'afterLeave'
     },
     leaveCancelled: function (el) {
     // handle cancellation
     }
    });
    八、組件
    1.注冊
    // 定義
    var MyComponent = Vue.extend({
     template: '<div>A custom component!</div>'
    });
    // 注冊
    Vue.component('my-component', MyComponent);
    // 創(chuàng)建根實例
    new Vue({
     el: '#example'
    });
    <div id="example">
     <my-component></my-component>
    </div>
    或者直接寫成:
    Vue.component('my-component', {
      template: '<div>A custom component!</div>'
    });
     // 創(chuàng)建根實例
    new Vue({
     el: '#example'
    });
    <div id="example">
      <my-component></my-component>
    </div>
    2.使用prop 傳遞數(shù)據(jù)
    實例一:
    Vue.component('child', {
     // 聲明 props
     props: ['msg'],
     // prop 可以用在模板內(nèi)
     // 可以用 `this.msg` 設(shè)置
     template: '<span>{{ msg }}</span>'
    });
    <child msg="hello!"></child>
    實例二:
    Vue.component('child', {
     // camelCase in JavaScript
     props: ['myMessage'],
     template: '<span>{{ myMessage }}</span>'
    });
    <!-- kebab-case in HTML -->
    <child my-message="hello!"></child>
    3.動態(tài)props
    <div>
     <input v-model="parentMsg">
     <br>
     <child v-bind:my-message="parentMsg"></child>
    </div>
    使用 v-bind 的縮寫語法通常更簡單:
    <child :my-message="parentMsg"></child>
    4.Prop 綁定類型
    prop 默認(rèn)是單向綁定:當(dāng)父組件的屬性變化時,將傳導(dǎo)給子組件,但是反過來不會。這是為了防止子組件無意修改了父組件的狀態(tài)——這會讓應(yīng)用的數(shù)據(jù)流難以理解。不過,也可以使用 .sync 或 .once 綁定修飾符顯式地強(qiáng)制雙向或單次綁定:
    比較語法:
    <!-- 默認(rèn)為單向綁定 -->
    <child :msg="parentMsg"></child>
    <!-- 雙向綁定 -->
    <child :msg.sync="parentMsg"></child>
    <!-- 單次綁定 -->
    <child :msg.once="parentMsg"></child>
    其他實例:
    <modal :show.sync="showModal">
     <h3 slot="header">custom header</h3>
     </modal>
    </div>
    5.Prop 驗證
    組件可以為 props 指定驗證要求。當(dāng)組件給其他人使用時這很有用,因為這些驗證要求構(gòu)成了組件的 API,確保其他人正確地使用組件。此時 props 的值是一個對象,包含驗證要求:
    Vue.component('example', {
     props: {
     // 基礎(chǔ)類型檢測 (`null` 意思是任何類型都可以)
     propA: Number,
     // 必需且是字符串
     propB: {
      type: String,
      required: true
     },
     // 數(shù)字,有默認(rèn)值
     propC: {
      type: Number,
      default: 100
     },
     // 對象/數(shù)組的默認(rèn)值應(yīng)當(dāng)由一個函數(shù)返回
     propD: {
      type: Object,
      default: function () {
      return { msg: 'hello' }
      }
     },
     // 指定這個 prop 為雙向綁定
     // 如果綁定類型不對將拋出一條警告
     propE: {
      twoWay: true
     },
     // 自定義驗證函數(shù)
     propF: {
      validator: function (value) {
      return value > 10
      }
     },
     // 轉(zhuǎn)換函數(shù)(1.0.12 新增)
     // 在設(shè)置值之前轉(zhuǎn)換值
     propG: {
      coerce: function (val) {
      return val + '' // 將值轉(zhuǎn)換為字符串
      }
     },
     propH: {
      coerce: function (val) {
      return JSON.parse(val) // 將 JSON 字符串轉(zhuǎn)換為對象
      }
     }
     }
    });
    其他實例:
    Vue.component('modal', {
     template: '#modal-template',
     props: {
     show: {
      type: Boolean,
      required: true,
      twoWay: true
     }
     }
    });
    6.注冊
    // 定義
    var MyComponent = Vue.extend({
     template: '<div>A custom component!</div>'
    });
    // 注冊
    Vue.component('my-component', MyComponent);
    // 創(chuàng)建根實例
    new Vue({
     el: '#example'
    });
    <div id="example">
     <my-component></my-component>
    </div>
    或者直接寫成:
    Vue.component('my-component', {
      template: '<div>A custom component!</div>'
    });
     // 創(chuàng)建根實例
    new Vue({
     el: '#example'
    });
    <div id="example">
      <my-component></my-component>
    </div>
    7.使用prop 傳遞數(shù)據(jù)
    實例一:
    Vue.component('child', {
     // 聲明 props
     props: ['msg'],
     // prop 可以用在模板內(nèi)
     // 可以用 `this.msg` 設(shè)置
     template: '<span>{{ msg }}</span>'
    });
    <child msg="hello!"></child>
    實例二:
    Vue.component('child', {
     // camelCase in JavaScript
     props: ['myMessage'],
     template: '<span>{{ myMessage }}</span>'
    });
    <!-- kebab-case in HTML -->
    <child my-message="hello!"></child>
    8.動態(tài)props
    <div>
     <input v-model="parentMsg">
     <br>
     <child v-bind:my-message="parentMsg"></child>
    </div>
    使用 v-bind 的縮寫語法通常更簡單:
    ?
    1
    <child :my-message="parentMsg"></child>
    9.Prop 綁定類型
    prop 默認(rèn)是單向綁定:當(dāng)父組件的屬性變化時,將傳導(dǎo)給子組件,但是反過來不會。這是為了防止子組件無意修改了父組件的狀態(tài)——這會讓應(yīng)用的數(shù)據(jù)流難以理解。不過,也可以使用 .sync 或 .once 綁定修飾符顯式地強(qiáng)制雙向或單次綁定:
    比較語法:
    <!-- 默認(rèn)為單向綁定 -->
    <child :msg="parentMsg"></child>
    <!-- 雙向綁定 -->
    <child :msg.sync="parentMsg"></child>
    <!-- 單次綁定 -->
    <child :msg.once="parentMsg"></child>
    其他實例:
    <modal :show.sync="showModal">
     <h3 slot="header">custom header</h3>
     </modal>
    </div>
    10.Prop 驗證
    組件可以為 props 指定驗證要求。當(dāng)組件給其他人使用時這很有用,因為這些驗證要求構(gòu)成了組件的 API,確保其他人正確地使用組件。此時 props 的值是一個對象,包含驗證要求:
    Vue.component('example', {
     props: {
     // 基礎(chǔ)類型檢測 (`null` 意思是任何類型都可以)
     propA: Number,
     // 必需且是字符串
     propB: {
      type: String,
      required: true
     },
     // 數(shù)字,有默認(rèn)值
     propC: {
      type: Number,
      default: 100
     },
     // 對象/數(shù)組的默認(rèn)值應(yīng)當(dāng)由一個函數(shù)返回
     propD: {
      type: Object,
      default: function () {
      return { msg: 'hello' }
      }
     },
     // 指定這個 prop 為雙向綁定
     // 如果綁定類型不對將拋出一條警告
     propE: {
      twoWay: true
     },
     // 自定義驗證函數(shù)
     propF: {
      validator: function (value) {
      return value > 10
      }
     },
     // 轉(zhuǎn)換函數(shù)(1.0.12 新增)
     // 在設(shè)置值之前轉(zhuǎn)換值
     propG: {
      coerce: function (val) {
      return val + '' // 將值轉(zhuǎn)換為字符串
      }
     },
     propH: {
      coerce: function (val) {
      return JSON.parse(val) // 將 JSON 字符串轉(zhuǎn)換為對象
      }
     }
     }
    });
    其他實例:
    Vue.component('modal', {
     template: '#modal-template',
     props: {
     show: {
      type: Boolean,
      required: true,
      twoWay: true
     }
     }
    });
    11.使用slot分發(fā)內(nèi)容
    <slot> 元素作為組件模板之中的內(nèi)容分發(fā)插槽。這個元素自身將被替換。
    有 name 特性的 slot 稱為命名 slot。 有 slot 特性的內(nèi)容將分發(fā)到名字相匹配的命名 slot。
    例如,假定我們有一個 multi-insertion 組件,它的模板為:
    <div>
     <slot name="one"></slot>
     <slot></slot>
     <slot name="two"></slot>
    </div>
    父組件模板:
    <multi-insertion>
     <p slot="one">One</p>
     <p slot="two">Two</p>
     <p>Default A</p>
    </multi-insertion>
    渲染結(jié)果為:
    <div>
     <p slot="one">One</p>
     <p>Default A</p>
     <p slot="two">Two</p>
    </div>