component/index.js
// 定义用来做全局组件注册的插件
// 插件使用
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 = '11111'
// 2. 添加全局组件 / 全局指令 Vue.component Vue.directive
// 3. 添加实例方法或者属性 Vue.prototype.$http = funciton(){}
// 只要Vue构造函数能力所及 都可以完成插件
// 2. 插件的定义有几种?
// 俩种:1.对象定义法 2.函数定义法
// 3. Vue.use必须在什么地方执行?
// 必须在new Vue实例化之前
// 4. 执行Vue.use(插件)相当于做了什么事?
// 自动执行了install方法 并且把Vue构造函数实参传入
components/PageTools'
<template>
<el-card>
<div class="page-tools">
<!-- 左侧 -->
<div class="left">
<slot name="left" />
</div>
<div class="right">
<slot name="right" />
<!-- 右侧 -->
</div>
</div>
</el-card>
</template>
<script>
/**
结构复用型组件: 内容是变化 但是整体的页面结构是相同
封装的核心思路: 在结构不变的情况下 把那些可变的部分封装成插槽 slot
pageTools: 可变的地方 左边提示语 右边操作栏 -> 具名插槽
具体实现步骤:
1. 不管插槽 先实现静态的结构
2. 把变的部分修改成具名插槽
3. 组件测试 进行插槽内容的传入
优化:把当前组件编程全局可用的全局组件 核心方法:Vue.component 调用时机: main.js
*/
export default {
name: 'PageTools'
}
</script>
<style lang="scss" scoped>
.page-tools {
display: flex;
justify-content: space-between;
align-items: center;
::v-deep.tips {
line-height: 34px;
padding: 0px 15px;
border-radius: 5px;
border: 1px solid rgba(145, 213, 255, 1);
background: rgba(230, 247, 255, 1);
i {
margin-right: 10px;
color: #409eff;
}
}
}
</style>
min.js
// 注册插件
import componentPlugin from '@/components'
Vue.use(componentPlugin)
Vue 官方提供的常规方法
- 在Vue项目中
src/components
路径下补充创建文件夹名(xxx)/ index.vue
,在此vue组件中写入自己需要服用多次的代码结构 - 在
src/main.js
文件中
import Vue from 'vue'
// 引入封装的复用的组件 注意xxx组件名应采用大驼峰命名法,例如:PageTool
import xxx from '@/components/文件夹名(xxx)'
Vue.component('xxx',xxx) // 在全局用Vue.component()方法全局注册