Some thoughts on the elegant way of writing code - js, vue

1. Code optimization - reduce code redundancy

 getState(status) {
      switch (status) {
        case 1:
          return "整改中";
        case 2:
          return "已整改";
        case 3:
          return "进行中";
        case 4:
          return "已解除";
        case 5:
          return "持续存在";
      }
    },
 getState(status) {
      const table ={1:'整改中',2:'已整改',3:'进行中',4:'已解除',5:'持续存在'};
      return table[status];
    },
   getComtentName(arg) {
      /**if (arg == 1) {
        return "评论";
      }
      if (arg == 2) {
        return "督办";
      }
      if (arg == 3) {
        return "处置日志";
      }
      if (arg == 4) {
        return "编辑";
      }*/
      const nameInfo={1:'评论',2:'督办',3:'处置日志',4:'编辑'};
      return nameInfo[arg];
    },

Two, css across the effect

css代码

.edit {
  background-image: url(~@images/edit.png);
}
.edit:hover {
  background-image: url(~@images/edit-hover.png);
}





template里面
 <span
                        v-if="ele.submitState !== 1"
                        @click="goDetail(ele.id, 'edit')"
                        title="编辑"
                        class="handle edit"
                      ></span>

<img :src="sysNot" title="系统通知" alt="系统通知" @mouseover="sysNot = sysNotOld" @mouseout="sysNot = sysNot1"
              @click="changeSys" />




下面是script的data中定义

 sysNot: "/static/img/msg.png",
      sysNot1: "/static/img/msg.png",
      sysNotOld: "/static/img/msg-hover.png",

 <img :src="checkedUser" title="切换账号" alt="切换账号" @mouseover="$event.currentTarget.src=checkedUserHover" @mouseout="$event.currentTarget.src=checkedUser"
              @click="changeSys" />

3. Determine whether the current array has duplicate values

 // 判断是否有重复
      const beginLength = repeatJudge.length;
      const endLength = Array.from(new Set(repeatJudge)).length;
      if (beginLength != endLength) {
        return this.$message.warning("审批流程的审批人员选择重复");
      }

4. Reduce code redundancy when introducing pictures

original code

   <img
          v-if="item.approveState == 2"
          class="state"
          src="@/images/rejected.png"
          alt=""
        />
        <img
          v-if="item.approveState == 1"
          class="state"
          src="@/images/pass.png"
          alt=""
        />
        <img
          v-if="item.approveState == 3"
          class="state"
          src="@/images/canceled.png"
          alt=""
        />

After improvement 

   <img
          class="statusImg"
          :src="approveStateList[pageInfo.approveState]"
          alt=""
        />









data(){return{approveStateList: {
        2: require("@/images/rejected.png"),
        1: require("@/images/pass.png"),
        3: require("@/images/canceled.png")
      }}},


5. Use the new method of es6 to traverse the object

遍历普通对象var obj = {1:1,2:2};

使用for in 

for(var key in  obj){ 

console.log(key);//输出的是对象的key而不是下标

}

6. Compare whether two arrays containing objects are the same

对比两个数组是否相同

var arr1 =[1,5,4,8,0,{q:''},3,5,1,{c:''}];

var arr2 =[{q:''},3,5,1,1,5,4,8,0,{c:''},123456789];

console.log(JSON.stringify(arr1.sort())==JSON.stringify(arr2.sort()))

Seven, traverse the objects in the array

遍历数组里的对象

let arr =[{1:1},{1:2}];

for( var item of arr) {

console.log(item,item[1])//{1:1},1

}

Eight, watch monitoring usage scenarios

Scenes:

When clicking on the details from the list page, we saw that the interface was adjusted on the details page, but we found that there was a problem with the rendering of the subcomponents on the details page. The investigation found that the parent passed the child before the interface was adjusted, and the subcomponent obtained an empty object, so we directly judged that something happened question.

How to solve it, set the timer to delay the judgment of calling the subcomponent? No no no, this trick doesn't work when the internet speed is bad.

The subcomponent adjusts the detailed interface again? no need

Just use watch to monitor

vue2的watch监听用法

  watch:{

    'detail':{// 引号加不加都无所谓,detail监听的是data或props里命名的值

      immediate: true,//初次获取到值就执行

      deep: true,// 深度监听对象

      handler(){ //执行我们想要的操作

this.powerCN = this.judgeType();

      }

    }

  },

Nine, about the usage scenarios of the null value coalescing operator??

I always feel that || is more practical than ??, when the value is 0, false, '', I can go to the back, until one day I find out whether some id exists, when the id or status is 0, it is directly used by | |Skip, and 0??1 is better than 0||1. It only goes backwards when it judges that the previous value is null or undefined.

10. Optional Chaining Operators

The optional chain operator is really cool to use, but an old project built by vue-cli2 I accepted can’t use this. I think there may be a problem with the plug-in parsed by babel. After investigation, it turns out to be true. It is recommended to search online Just install a plug-in and configure it to use it.

In fact, most of the vue2 and vue3 projects now can use the optional chain operator without our separate configuration.

Reduced code redundancy, and recently found that it is even possible to determine whether an object exists and then call it;

Eleven, es9 new additions

1. Asynchronous iteration
await可以和for...of循环一起使用,以串行的方式运行异步操作

async function process(array) {

for await (let i of array) {

// doSomething(i);

}}
2. Array.flat()和Array.flatMap()
flat()

[1, 2, [3, 4]].flat(Infinity); // [1, 2, 3, 4]

flatMap()

[1, 2, 3, 4].flatMap(a => [a**2]); // [1, 4, 9, 16]

3. Logical operators and assignment expressions

Logical operators and assignment expressions, the new feature combines logical operators (&&, ||, ??) and assignment expressions while JavaScript’s existing compound assignment operators are:

a ||= b

//等价于

a = a || (a = b)



a &&= b

//等价于

a = a && (a = b)



a ??= b

//等价于

a = a ?? (a = b)

4. Number separator

Number separator, you can create a visual separator between numbers, and use _ underscore to separate numbers to make numbers more readable

const money = 1_000_000_000;

//等价于

const money = 1000000000;



1_000_000_000 === 1000000000; // true

5. Object.assign method (object merge)
//Object.assign 静态方法 提取对象所有的属性及方法,方法合并为一个对象 返回一个新对象

var newObj = Object.assign({a:'a'},{b:'b'},{c:'c'})

console.log(newObj);  //返回值为 {a:'a',b:'b',c:'c'}

6. The spread operator (…)

Used to take out all traversable properties of the parameter object and copy them to the current object

// 1、拷贝对象(深拷贝)

let p1 = { name: "Amy", age: 15 }

let someone = { ...p1 }

console.log(someone)  //{name: "Amy", age: 15}

12. The template template directly loops through objects


    <div v-for="item,key,index in test" :key='key'><span>{
   
   {key}}</span></div>





test:{

        "2023-06-29": [

            {

                "id": 60162,

                "hintId": "542473209950375956",

                "createTime": "2023-06-29T06:07:35.000+0000",

                "commentName": "河北省人力资源部操作员",

                "orgId": "212942",

                "orgName": "中国人寿河北省分公司",

                "deptId": "90176",

                "deptName": "人力资源部",

                "content": "河北省人力资源督办",

                "commentType": 2

            }

        ]

    }

You can also loop through Object.entries(this.coverList) after conversion

Guess you like

Origin blog.csdn.net/aZHANGJIANZHENa/article/details/130981422