vue全局组件全局插件开发技巧

很多时候我们开发一个组件需要频繁使用的时候,最好的方法就是进行全局注册,这样可以更方便使用。

这篇文章就是讨论一下全局注册组件或插件技巧

全局组件注册方式:

直接在入口main.js引入注册

import  LoadingView from  './components/Loading.vue';
Vue.component('Loading',LoadingView);

  

全局插件注册方法:

Vue的插件应当有一个公开方法 install 。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

export default {
    install (Vue, options) {
        // 具体逻辑
    }
}

我们需要在入口mian.js中引入  

import pluginsUtil from './pluginsUtil' Vue.use(pluginsUtil)

插件的逻辑是use()即执行一遍install函数,这个时候我们可以给VUE写入全局功能,主要依靠下面五个方法
1、使用Vue.mixin全局混入数据
mixin可以混入一个对象到全局中,让全局都可以读取,需要注意的是这个对象数据是每个组件独享的,修改只能在当前组件生效;
Vue.mixin({
            data () {
                return {
                    global:'www.aiyexue.com'
                }
            }
        })

2、通过原型链往全局写入方法

比如一个加载插件,我们可以在全局写入显示和关闭函数

Vue.prototype.$loading.show=function(){
  show();    
}
Vue.prototype.$loading.hide=function(){
  hide();    
}

3、定义全局过滤器使用Vue.filter

Vue.filter('addZero', function (num) {
            return num + '.00'
        })

4、定义全局指令Vue.directive

Vue.directive('myfocus', {
            inserted: function (el) {
                el.focus()
            }
        })

5、引入全局主机进行混合操作

以上方法可以混合起来开发强大的功能插件,并且我们可以混入全局组件

import loading from './loading.vue'
export default {
    install (Vue, options) {
        Vue.component('Loading',loading);
        Vue.prototype.$loading.show=function(){
      //逻辑 } Vue.prototype.$loading.show=function(){
      //逻辑 } } }

  

 
 
posted @ 2019-08-07 16:57  每日夜学,日渐憔悴  阅读(714)  评论(0编辑  收藏  举报