介绍
在vue
的main.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
作为参数传入。
我们分两点来看:
- 如果
Vue.use()
中的参数是一个function
函数,那么函数的参数是Vue
对象。 - 如果
Vue.use()
中的参数是一个Object
对象,那么这个对象必须提供一个install
方法,install
方法的参数就是Vue
。
Demo演示
我们通过以下两个Demo来分别演示一下上面说的两种情况。
Object
对象
我们通过自定义一个主键的形式进行演示说明。
创建项目
vue init webpack-simple custom-global-component
一路回车,然后执行
npm run dev
如果项目能正常启动代表创建成功。
创建组件
创建components
文件夹,并创建loading.vue
及index.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)
没啥说的吧