小tip:
当网页中有多种情况的操作按钮,这些按钮的功能和样式相同,但每个页面的所需的功能不同,且后续对按钮功能可能还会有相应的更改,故做了这样的封装。
一、封装
OperateBtn.vue
<template>
<el-button
v-for="btn in btns"
:key="btn.value"
@click="handleClickBtn(btn.value)"
:type="btn.type"
:icon="btn.icon"
>{{ btn.name }}
</el-button>
</template>
<script>
export default {
props: {
btns: {
type: Array,
default() {
return [];
}
}
},
methods: {
handleClickBtn(name) {
this.$emit("handleClickBtn", name);
}
}
};
</script>
二、使用
testOperate.vue
<template>
<div class="test-operate">
<comn-operate :btns="btns1" @handleClickBtn="handleClickBtn1" />
<br />
<br />
<br />
<comn-operate :btns="btns2" @handleClickBtn="handleClickBtn2" />
<br />
<br />
<br />
<comn-operate :btns="btns3" @handleClickBtn="handleClickBtn3" />
</div>
</template>
<script>
import comnOperate from "@/OperateBtn.vue";
import { getOperateInfo } from "@/enums/OperateBtn.js"; // 引入封装的getOperateInfo 方法,获取该页的btns
export default {
data() {
return {
btns1: [],
btns2: [],
btns3: []
};
},
mounted() {
this.btns1 = getOperateInfo("THE_FIRST_TYPE");
this.btns2 = getOperateInfo("THE_SECOND_TYPE");
this.btns3 = getOperateInfo("THE_THIRD_TYPE");
},
components: {
comnOperate
},
methods: {
handleClickBtn1(name) {
console.log("我是第一种情况:", name);
},
handleClickBtn2(name) {
console.log("我第二:", name);
},
handleClickBtn3(name) {
console.log("我第三:", name);
}
}
};
</script>
OperateBtn.js
const OPERATE_ARRS = [
{
name: "添加",
value: "add",
icon: "el-icon-plus",
type: "default"
},
{
name: "修改",
value: "edit",
type: "warning",
icon: "el-icon-edit"
},
{
name: "删除",
value: "del",
type: "danger",
icon: "el-icon-delete"
},
{
name: "移动",
value: "move",
type: "primary",
icon: "el-icon-rank"
},
{
name: "查看",
value: "view",
type: "info",
icon: "el-icon-view"
},
{
name: "保存",
value: "save",
type: "success",
icon: "el-icon-document"
}
];
const ACTION_NAME = {
THE_FIRST_TYPE: ["添加", "修改", "删除", "查看"],
THE_SECOND_TYPE: ["修改", "删除", "保存"],
THE_THIRD_TYPE: ["查看", "修改", "移动"]
};
// 注意type用于区分是何种类型 的btn ,为配合btn顺序,必须先遍历names;
function getOperateInfo(type) {
let result = [];
const names = ACTION_NAME[type];
names.forEach(name => {
OPERATE_ARRS.forEach(val => {
if (val.name === name) {
result.push(val);
}
});
});
return result;
}
export { getOperateInfo };