Vue 插件编写

2017-12-27  本文已影响0人  Osmond_wang

vue插件介绍

2. 插件分类   

插件类型

主要注册与绑定机制如下:

export default{

install(Vue,options){

Vue.myGlobalMethod= function(){     // 1. 添加全局方法或属性,如: vue-custom-element

        // 逻辑...

}

Vue.directive('my-directive',{         

// 2. 添加全局资源:指令/过滤器/过渡等,如 

        vue-touchbind(el,binding,vnode,oldVnode){

            // 逻辑...

        }

})

Vue.mixin({  created:function(){  
        // 3. 通过全局 mixin方法添加一些组件选项,如: vuex      
        // 逻辑...
    }
})

Vue.prototype.$myMethod=function(options){  
            // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现
            // 逻辑...
        }
    }
}

3. 插件使用

    在plugins.js中我们仅仅编写了一个插件的空壳子,假如现在需要全局注册该插件,我们可以在入口文件,比如main.js中注册:

...

import Vue from'vue'

import MyPlugin from './plugins/plugins.js'

Vue.use(MyPlugin);

...

通过全局方法 Vue.use() 即可使用该插件,其自动会调用install方法。Vue.use会自动阻止注册相同插件多次,届时只会注册一次该插件。

上一篇下一篇

猜你喜欢

热点阅读