美文网首页让前端飞
关于Vue.prototype 和 vue.use()

关于Vue.prototype 和 vue.use()

作者: littleyu | 来源:发表于2019-04-29 10:45 被阅读4次

首先,不管你采用哪种方式,最终实现的调用方式都是

vm.api()

也就是说,两种方法,实现的原理都是在 Vue.prototype 上添加了一个方法。所以结论是“没有区别”

再来说说 Vue.use() 到底干了什么。

我们知道,Vue.use() 可以让我们安装一个自定义的Vue插件。为此,我们需要声明一个install 函数

// 创建一个简单的插件 say.js
var install = function(Vue) {
  if (install.installed) return // 如果已经注册过了,就跳过
  install.installed = true

  Object.defineProperties(Vue.prototype, {
    $say: {
      value: function() {console.log('I am a plugin')}
    }
  })
}
module.exports = install

然后我们要注册这个插件

import say from './say.js'
import Vue from 'vue'

Vue.use(say)

这样,在每个 Vue 的实例里我们都能调用 say 方法了。

我们来看 Vue.use 方法内部是怎么实现的

Vue.use = function (plugin) {
  if (plugin.installed) {
    return;
  }
  // additional parameters
  var args = toArray(arguments, 1);
  args.unshift(this);
  if (typeof plugin.install === 'function') {
    plugin.install.apply(plugin, args);
  } else {
    plugin.apply(null, args);
  }
  plugin.installed = true;
  return this;
};

其实也就是调用了这个 install 方法而已。

相关文章

  • 关于Vue.prototype 和 vue.use()

    首先,不管你采用哪种方式,最终实现的调用方式都是 也就是说,两种方法,实现的原理都是在 Vue.prototype...

  • vue.use和vue.prototype的区别

    不是为了vue写的插件(插件内要处理)不支持Vue.use()加载方式 非vue官方库不支持new Vue()方式...

  • 关于Vue.use()

    在vue开发当中,Vue.use()用于引入组件。下面是use.js的源码··· }} ···从源码中可以看到,u...

  • 关于Vue.use

    先看下源码 从源码中我们可以发现vue首先判断这个插件是否被注册过,如果已经注册过就直接 return 这个插件。...

  • vue项目中prototype的应用

    js通过原型链可以实现继承那么我们可以对Vue.prototype进行操作,对Vue.prototype添加属性或...

  • Vue.use源码

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

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

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

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

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

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

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

  • 关于Vue.use()详解

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

网友评论

    本文标题:关于Vue.prototype 和 vue.use()

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