Vue.use()的用法

Laughing
2021-05-07 / 2 评论 / 1,031 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月18日,已超过341天没有更新,若内容或图片失效,请留言反馈。

介绍

vuemain.js中,我们经常使用Vue.use(xx)方法。比如我们引入elementUI,在main.js中,我们一般通过如下代码引入:

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

[alt type="error"]需要先通过npm i element-ui -S安装elementUI[/alt]
原来在开发时,一直都是这么用,但是基本没留意过为什么这么弄。

官方解释

安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。
什么意思呢?
Vue.use() 中的参数必须是一个function函数或者是一个Object对象,如果是对象的话,必须在对象中提供一个install方法。之后会将 Vue 作为参数传入。
我们分两点来看:
  1. 如果Vue.use() 中的参数是一个function函数,那么函数的参数是Vue对象。
  2. 如果Vue.use() 中的参数是一个Object对象,那么这个对象必须提供一个install方法,install方法的参数就是Vue

Demo演示

我们通过以下两个Demo来分别演示一下上面说的两种情况。

Object对象

我们通过自定义一个主键的形式进行演示说明。

创建项目

vue init webpack-simple custom-global-component

一路回车,然后执行

npm run dev

如果项目能正常启动代表创建成功。

创建组件

创建components文件夹,并创建loading.vueindex.js文件。
目录结构如下
loading.vue只是一个简单的组件,代码如下

<template>
    <div>
        Laoding...
    </div>
</template>

<script>
export default {
    
}
</script>

index.js,我们引入并注册定义的组件。

import LoadingComponent from './loading.vue'
const Loading = {
    install:function(Vue){
        Vue.component('Loading',LoadingComponent)
    }
}
export default Loading

main.js中通过Vue.use()调用。

import Loading from './components/loading'

Vue.use(Loading)

使用

App.vue中使用我们的组件。

<template>
  <div id="app">
    <Loading/>
  </div>
</template>

function函数

创建函数

function demo(Vue){
    console.log(Vue)
}
export default demo

引入

main.js中引入函数。

import demo from './utils/func'

Vue.use(demo)
0

评论 (2)

取消
  1. 头像
    Laughing 作者
    Windows 10 · Google Chrome

    画图

    回复
    1. 头像
      Laughing 作者
      Windows 10 · Google Chrome
      @ Laughing

      表情

      回复
  2. 头像
    Laughing 作者
    Windows 10 · Google Chrome

    没啥说的吧

    回复