vue.use 是什么?
官方对 Vue.use() 方法的说明: 通过全局方法 Vue.use() 使用插件, Vue.use 会自动阻止多次注册相同插件, 它需要在你调用 new Vue() 启动应用之前完成, Vue.use() 方法至少传入一个参数, 该参数类型必须是 Object 或 Function, 如果是 Object 那么这个 Object 需要定义一个 install 方法, 如果是 Function 那么这个函数就被当做 install 方法. 在 Vue.use() 执行时 install 会默认执行, 当 install 执行时第一个参数就是 Vue, 其他参数是 Vue.use() 执行时传入的其他参数. 就是说使用它之后调用的是该组件的 install 方法.
Vue.use() 的源码中的逻辑
- export function initUse (Vue: GlobalAPI) {
- Vue.use = function (plugin: Function | Object) {
- const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
- if (installedPlugins.indexOf(plugin)> -1) {
- return this
- }
- const args = toArray(arguments, 1)
- args.unshift(this)
- if (typeof plugin.install === 'function') {
- plugin.install.apply(plugin, args)
- } else if (typeof plugin === 'function') {
- plugin.apply(null, args)
- }
- installedPlugins.push(plugin)
- return this
- }
- }
在源码中首先限制了它传入的值的类型只能是 Function 或者 Object, 然后判断了该插件是不是已经注册过, 防止重复注册, 然后调用了该插件的 install 方法, 源码中也有介绍到 Vue.use() 可以接受多个参数的, 除第一个参数之后的参数我们都是以参数的形式传入到当前组件中.
Vue.use() 什么时候使用?
它在使用时实际是调用了该插件的 install 方法, 所以引入的当前插件如果含有 install 方法我们就需要使用 Vue.use(), 例如在 Vue 中引用 Element 如下:
- import Vue from 'vue'
- import Element from 'element-ui'
- Vue.use(Element)
因为在 Element 源码中会暴露除 install 方法, 所以才需要用 Vue.use() 引入.
我们也可以在自己的 vue 项目中自己定义一个 install 方法, 然后通过 Vue.use() 方法来引入测试一下:
- const plugin = {
- install() {
- alert("我是 install 内的代码")
- },
- }
- import Vue from "vue"
- Vue.use(plugin) // 页面显示 "我是 install 内的代码"
当我们打开页面就会弹出 "我是 install 内的代码" 提示.
更多 vue.js 相关知识, 可访问 Vue.JS 答疑 https://www.html.cn/qa/vue-js/ 栏目!!
来源: http://www.css88.com/qa/vue-js/15736.html