关于vue.js:Vueuse-源码解析及使用

29次阅读

共计 1656 个字符,预计需要花费 5 分钟才能阅读完成。

1、官网文档阐明:https://cn.vuejs.org/v2/api/#Vue-use

2、找到源码看
Vue.use(plugin)
这个 plugin,要么是蕴含 install 办法的对象,要么自身就是一个函数。第一个参数始终是 Vue 对象。

function initUse (Vue) {Vue.use = function (plugin) {var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
    if (installedPlugins.indexOf(plugin) > -1) { // 判断插件有没有被注册
      return this
    }

    // additional parameters
    var args = toArray(arguments, 1);
    args.unshift(this); //this 指向 Vue 对象,所以数组参数第一个始终是 vue 对象
    if (typeof plugin.install === 'function') {plugin.install.apply(plugin, args); // 整顿好的数组参数传给 install 办法,this 指向为 plugin 本人
    } else if (typeof plugin === 'function') {plugin.apply(null, args); // plugin 是函数的话,间接调用,传入参数。留神:其内 this 为 null
    }
    installedPlugins.push(plugin); 
    return this
  };
}
/**
 * Convert an Array-like object to a real Array.
 */
function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {ret[i] = list[i + start];
  }
  return ret
}

3、通过下面可知编写插件的两种办法,应用:
1)、蕴含 install 办法的对象(举荐),逻辑性比拟强的比拟适宜, 编写灵便,拓展性也高,最初通过 install 办法裸露给 Vue 对象

const plugin = {
    //this 指向 plugin 对象自身
    install() {
      // 巴拉巴拉一系列操作
      let conso = this.handleConsole() 
      console.log(this.handleConsole)
      console.log(conso)
      console.log(this.data)
    },
    handleConsole() {console.log('handleConsole');
      let comdata = '吃葡萄不吐葡萄皮'
      return comdata
    },
    data: [1,2,3]
}
export default plugin

浏览器打印:

2)、一个函数,适宜一般简略的

// 比方自定义全局组件,对立一个文件
// globalComponents.js
import Vue from 'vue';
import pHeader from './components/pheader'
import pFooter from './components/pfooter'
function plugin() {
    //this 为 null
  Vue.component('pHeader', pHeader);
  Vue.component('pFooter', pFooter);
}
export default plugin

// 应用 main.js
import Vue from 'vue'
import GlobalComponents from './globalComponents'
Vue.use(GlobalComponents);

// 而后就能够全局应用自定义的组件了。

4、还有个问题:
该办法须要在调用 new Vue() 之前被调用。那么为什么要在之前调用的?
简略的了解:如果在 new Vue() 之后调用,那么你的插件的内容就来不及增加到 Vue 中。

正文完
 0