vue2 混入 (mixin) 带来的小惊喜

发布时间 2023-12-21 15:24:19作者: Jason.裕哥

最近在review自己写的代码时发现,在很多的地方都用了以下的代码块

 1 async initCode() {
 2             const resSource = await this.$API.syscode.list.get({
 3                 typeCode: "source",
 4                 type: 3,
 5             });
 6             if (resSource.code == 200) {
 7                 resSource.data.forEach((e) => {
 8                     this.sourceOptions.push({
 9                         label: e.name,
10                         value: e.id,
11                     });
12                 });
13             }
14             const resLevel = await this.$API.syscode.list.get({
15                 typeCode: "level",
16                 type: 3,
17             });
18             if (resLevel.code == 200) {
19                 resLevel.data.forEach((e) => {
20                     this.levelOptions.push({
21                         label: e.name,
22                         value: e.id,
23                     });
24                 });
25             }
26             const resIndustry = await this.$API.syscode.list.get({
27                 typeCode: "industry",
28                 type: 3,
29             });
30             if (resIndustry.code == 200) {
31                 resIndustry.data.forEach((e) => {
32                     this.industryOptions.push({
33                         label: e.name,
34                         value: e.id,
35                     });
36                 });
37             }
38             const resCity = await this.$API.syscity.list.get();
39             let _tree = [];
40             resCity.data.some((m) => {
41                 _tree.push({
42                     id: m.id,
43                     value: m.name,
44                     label: m.name,
45                     parentId: m.parentId,
46                 });
47             });
48             this.cityOptions = this.$TOOL.changeTree(_tree);
49         },

其中主要是调用 await this.$API.syscode.list.get  api接口返回一组可用的数组数据,这种代码在项目存在很多所以想有没有办法优化一下。

于是在vue官方文档中找到了这个 混入 — Vue.js (vuejs.org)  

同时询问了chatgpt同样给出了相同解决方案,于是根据文档写一个了,并运行成,惊喜不错。

第一步:新建一个  mixin.js,写如下代码

export default {
    data() {
        return {};
    },
    methods: {
        async mixinCodeSelect(code, type) {
            const res = await this.$API.syscode.list.get({
                typeCode: code,
                type: type,
            });
            let arr = [];
            if (res.code == 200) {
                res.data.forEach((e) => {
                    arr.push({
                        label: e.name,
                        value: e.id,
                    });
                });
            }
            return arr;
        },
    },
};

该方法是返回一个基于下拉框的数据,调用 mixinCodeSelect 方法需要传入2个参数。

第二步:在vue页面中使用

引入  import mixin from '@/utils/mixin.js';

在methods中调用minxin里面的方法即可,如下:

mounted() {
		this.initCode();
	},
	methods: {
		async initCode() {
			this.typeIdOptions=await this.mixinCodeSelect('contract-type',3);
		},
}

  

这样就简单很多了,代码看着也清爽了。