Vue.use()作用
官方文档中提到,Vue.use()可以用来注册全局的插件。使用Vue.use()后可以使得插件能够在项目的任意位置上使用。
那么什么时候使用Vue.use()呢?其实官方文档中也给出了很详细的答案,就是当一个插件对象或者函数,拥有install方法时,就使用Vue.use()。调用Vue.use()时会调用插件的install方法,使得其能够全局使用。
Vue的使用场景
- ElementUI、VueRouter等官方插件的使用
在vue官方社区中提供了一系列辅助开发的插件,其中就有很多插件具有install方法,比如ElementUI和VueRouter,我们使用Vue.use()进行引入。
import Vue from 'vue'
import VueRouter from 'vue-router';
import Element from 'element-ui'
Vue.use(VueRouter);
Vue.use(Element);
- 自定义插件,并提供install方法
除了使用官方的插件,我们也可以自定义一些含有install方法的插件
import Icon from '../components/icon/index'
const IconConponents = {
// install 是默认的方法。当外界在 use 这个组件的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
install: function (Vue) {
Vue.component('Icon', Icon)
}
}
// 导出
export default IconConponents
在main.js中进行注册插件
import Icon from './global'
Vue.use(Icon)