随着业务的增加,在main.js注册了太多的全局组件,导致main.js结构混乱,并且main.js不适宜放太多的代码,所以把全局组件统一进行注册
一般注册全局组件插件卸载components文件夹中,因为components放的是全局通用组件
对象定义法
// 定义用来做全局组件注册的插件
// 插件使用
import PageTools from '@/components/PageTools'
// 1. 插件的定义
// 1. 对象定义法 2.函数定义法[当插件是以函数定义时,函数本身会被作为install自动执行]
const plugin = {
// 固定的
install(Vue) {
// Vue形参: Vue的构造函数
console.dir(Vue)
// Vue.component -> 全局注册
Vue.component(PageTools.name, PageTools)
}
}
// 2. 插件的注册 实例化之前 调用Vue.use(plugin)
// 重要: 一旦我们调用了Vue.use(plugin)相当于自动执行了插件对象内部的install
// 并且把Vue构造函数当成实参传入
export default plugin
// 1. 什么是插件?
// 只要你想给Vue扩展一些全局的功能 就可以通过插件来做
// 1. 添加全局的静态方法或者属性 Vue.title = '柴柴老师'
// 2. 添加全局组件 / 全局指令 Vue.component Vue.directive
// 3. 添加实例方法或者属性 Vue.prototype.$http = funciton(){}
// 只要Vue构造函数能力所及 都可以完成插件
// 2. 插件的定义有几种?
// 俩种:1.对象定义法 2.函数定义法
// 3. Vue.use必须在什么地方执行?
// 必须在new Vue实例化之前
// 4. 执行Vue.use(插件)相当于做了什么事?
// 自动执行了install方法 并且把Vue构造函数实参传入
函数定义法
// 定义用来做全局组件注册的插件
// 插件使用
import PageTools from '@/components/PageTools'
// 1. 插件的定义
// 1. 对象定义法 2.函数定义法[当插件是以函数定义时,函数本身会被作为install自动执行]
const plugin = (Vue)=>{
// Vue形参: Vue的构造函数
console.dir(Vue)
// Vue.component -> 全局注册
Vue.component(PageTools.name, PageTools)
}
export default plugin
注册完 插件后在main.js中导入组件,使用Vue.use()注册插件
// 注册插件
import componentPlugin from '@/components'
Vue.use(componentPlugin)
写在new Vue之前
new Vue({
el: '#app',
router,
store,
render: h => h(App)
// 类比为template模板 把app根组件进行渲染挂载 app根组件一单渲染
// 底层的所有的子孙组件也会一起渲染
})
使用的时候直接使用就可以
<template>
<page-tools>
<template #left>
<div class="tips">
<i class="el-icon-info" />
<span>本月: 社保在缴 公积金在缴</span>
</div>
</template>
<template #right>
<el-button type="warning" size="small" @click="$router.push('/import')">excel导入
</el-button>
<el-button type="danger" size="small">excel导出</el-button>
<el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
</template>
</page-tools>
<template>