vue.use(xxx)即安装xxx插件,方法本质上是在调用xxx内部的install()方法。
拿组件注册举例,平时引入组件是在vue文件内import进去,然后注册到component里;但是我们使用ElementUI时只需要use某个组件就能使用了,其本质就是在install方法内部用Vue.component()注册了组件。
举个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <template> <t-label/> <t-input/> </template> <script> import TLabel from './xxx/Tlabel.vue' import TInput from './xxx/Tlabel.vue' export default{ components:[ TLabel, TInput ] } </script>
|
插件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import TLabel from './xxx/Tlabel.vue' import TInput from './xxx/Tlabel.vue' const components = [TLabel,TInput] const plugins = { install(Vue){ components.forEach(component=>{ Vue.component(component.name,component) }) console.log('插件install方法调用') }, test{ console.log('test方法调用') } } export default plugins
|
然后mainjs注册插件:
1 2 3
| import plugins from 'xxx' Vue.use(plugins) ...
|
注册完成后,页面文件即使不注册组件也能使用组件。