美文网首页Vue
Vue - Vue.use()

Vue - Vue.use()

作者: ElricTang | 来源:发表于2019-10-27 21:27 被阅读0次

安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

一. 作用:全局注入插件(如vue-router)

  • 插件写法,第一个参数是vue对象,第二个是额外参数(配置对象)
MyPlugin.install = function (Vue, options) {

}
  • 插件使用,第一个参数是插件,后面是额外参数(配置对象)
Vue.use(MyPlugin, { someOption: true })

二. Vue.use()源码:

  • installedPlugins存放的是当前vue实例中安装过的插件数组。
  • 判断是否已经安装过,没有安装过继续往下走
      if (installedPlugins.indexOf(plugin) > -1) {
        return this
      }
  • 取出除了第一个参数外的参数(第一个参数是指当前安装的插件),
    源码上写了注释additional parameters(额外参数)。这里的toArray方法是用于格式化参数的,主要为了将配置对象转换为参数数组,并将vue对象插入到参数数组第一位。
      // additional parameters
      var args = toArray(arguments, 1);
      args.unshift(this);
  • 这里有一个分支,分别针对两种不同情况。
      1. 当前插件是一个对象,该对象拥有一个install方法。这时候执行install,绑定this为plugin,并传入额外参数。
      1. 当前插件就是一个函数。直接执行该函数,绑定this为null,并传入额外参数。
      if (typeof plugin.install === 'function') {
        plugin.install.apply(plugin, args);
      } else if (typeof plugin === 'function') {
        plugin.apply(null, args);
      }
  • 最后,更新已安装插件的数组,加入新插件。(插件不能重复安装)
installedPlugins.push(plugin);

相关文章

  • Vue.use() 注册插件(个人笔记)

    Vue.use是什么? 官方对 Vue.use() 方法的说明:通过全局方法 Vue.use() 使用插件,Vue...

  • Vue.use源码

    官方对 Vue.use() 方法的说明: 通过全局方法 Vue.use() 使用插件;Vue.use 会自动阻止多...

  • Vue.use, Vue.component,router-vi

    ? Vue.use Vue.use 的作用是安装插件 Vue.use 接收一个参数 如果这个参数是函数的话,Vue...

  • vue.use()和vue.extend()

    经常会见到vue.use()和vue.extend(),到底什么意思呢? 一、vue.use() 经常会用到Vue...

  • 为什么axios不是使用的vue.use()

    问题 相信很多人在用Vue使用别人的组件时,会用到Vue.use()。例如:Vue.use(VueRouter)、...

  • 关于Vue.use()详细说明

    问题 相信很多人在用Vue使用别人的组件时,会用到Vue.use()。例如:Vue.use(VueRouter)、...

  • 关于Vue.use()详解

    问题相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter)...

  • VUE.use详解

    问题 相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter...

  • 关于Vue.use()详解

    问题 相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter...

  • 彻底弄懂 Vue.use() 方法

    相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter)、V...

网友评论

    本文标题:Vue - Vue.use()

    本文链接:https://www.haomeiwen.com/subject/rnumvctx.html