Vue的混合、自定義指令和插件

可複用性和組合

混合

混合 (mixins) 是一種分發 Vue 組件中可複用功能的很是靈活的方式。混合對象能夠包含任意組件選項。以組件使用混合對象時,全部混合對象的選項將被混入該組件自己的選項。html

圖片描述

<div id="app">
    <popup></popup>
    <more></more>
</div>
<script type="text/x-template" id="popup-tmp">
    <div>
        <input type="button" value="彈出" v-on:click="togg">
        <div class="popup" v-show="viv">
            2333
            <input type="button" v-on:click="hide" value="shutDown">
        </div>
    </div>
</script>

<script type="text/x-template" id="more-tmp">
    <div>
        <a @mouseover="show" @mouseout="hide">更多</a>
        <ul v-show="viv">
            <li>從前有座山</li>
            <li>山上有座廟</li>
            <li>老和尚</li>
            <li>wot</li>
        </ul>
    </div>
    
</script>
<script>
    var base={//定義一個混合對象
        data:function(){
            return{
                viv:false
            }
        },
        methods:{
            togg:function(){
                this.viv=!this.viv
            },
            hide:function(){
                this.viv=false
            },
            show:function(){
                this.viv=true
            }
        }
    }
    var Popup={
        template:'#popup-tmp',
        mixins:[base],//使用混合對象
        data:function(){
            return {viv:true}
        }
    }

    var Menu={
        template:"#more-tmp",
        mixins:[base]//使用混合對象
    }
    new Vue({
        el:'#app',
        components:{
            "popup":Popup,
            "more":Menu
        }
    })
</script>

在上面的例子中,咱們建立了一個點擊彈出框和一個滑過彈出框,由於其調用的數據和方法都是重複的,所以就定義一個混合對象,讓兩個不一樣的彈出框分別調用。node

官方例子:app

// 定義一個混合對象
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}
// 定義一個使用混合對象的組件
var Component = Vue.extend({
  mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"

自定義指令

Vue容許自定義指令。ide

舉個例子,如今這裏有個input輸入框,當頁面加載時,輸入框就已經獲取焦點,並將輸入框固定在視口的某一位置上:this

Vue.directive('focus',{
    inserted:function(el){
        el.style.position="fixed";
        el.style.left="10px";
        el.style.top="10px";
        el.focus()
    }
})

這樣在模板中就能夠使用了spa

<input type="text" v-focus>

插件

插件的開發

Vue.js 的插件應當有一個公開方法 install 。這個方法的第一個參數是 Vue 構造器 , 第二個參數是一個可選的選項對象:prototype

var Myplugin={};
MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或屬性
  Vue.myGlobalMethod = function () {
    // 邏輯...
  }

  // 2. 添加全局資源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 邏輯...
    }
    ...
  })

  // 3. 注入組件
  Vue.mixin({
    created: function () {
      // 邏輯...
    }
    ...
  })

  // 4. 添加實例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 邏輯...
  }
}

使用插件

Vue.use(MyPlugin)
相關文章
相關標籤/搜索