一、初始化项目
在插件根目录通过npm init -y 生成 package.json文件 ,并修改配置
二、封装组件并install为插件
tablePlugin.vue 组件文件
<template>
<div class="table_set">
<el-dropdown
class="drop_column"
trigger="click"
:hide-on-click="false"
@command="handleCommand"
>
<span class="el-dropdown-link">
<i class="el-icon-setting"></i>
</span>
<el-dropdown-menu slot="dropdown">
<template v-for="item in columns">
<el-dropdown-item :command="item">
<el-checkbox v-model="item.checked" @change="handleCommand(item)"></el-checkbox>
{{item.title}}
</el-dropdown-item>
</template>
</el-dropdown-menu>
</el-dropdown>
<el-table :data="data" style="width: 100%" border>
<template v-for="item in tableColumns">
<el-table-column :key="item.prop" :prop="item.prop" :label="item.title" :width="item.width"></el-table-column>
</template>
</el-table>
</div>
</template>
<script>
export default {
name: 'tablePlugin',
props: {
data: {
type: Array,
default: [],
},
columns: {
type: Array,
default: [],
},
},
computed: {
tableColumns() {
return this.columns.filter((item) => item.checked)
},
},
data() {
return {}
},
methods: {
handleCommand(item) {
item.checked = !item.checked
},
},
}
</script>
<style lang="scss">
.table_set {
position: relative;
.drop_column {
position: absolute;
right: 20px;
z-index: 10;
top: 14px;
}
}
</style>
index.js vue.use() 会触发 install
import tablePlugin from './tablePlugin.vue'
// const comment = {
// install: function (Vue) {
// Vue.component(table_plugin.name, table_plugin)
// }
// }
// global 情况下 自动安装
// if (typeof window !== 'undefined' && window.Vue) {
// window.Vue.use(comment)
// }
// 导出模块
// export default comment
export default { //如果有多个组件可以通过数组循环
install: (app, opts) => {
app.component(tablePlugin.name, tablePlugin)
}
}
三、当前项目下使用
<tablePlugin :data="tableData" :columns="columns"></tablePlugin> //项目中就可以直接使用
四、登录npm
五、发布song_table_plugin插件
六、其他项目使用 npm i song_table_plugin
注意:插件中使用的依赖,也需要打包出去,否则使用的项目没有安装插件使用的依赖将会报错... 或者使用的项目中引入需要的依赖