Skip to content
On this page

前端开发规范

Vue 规范

  • 尽量不要使用 watch 监听,如果是必须情况,也不要监听整个对象

BAD

js
watch: {
  allData: {
    handler() {
      ...
    },
    deep: true,
  },
}
1
2
3
4
5
6
7
8

GOOD

js
watch: {
  'allData.xx': function () {
    ...
  },
},
1
2
3
4
5
  • 不要使用单个单词作为组件名,因为这可能和未来的 HTML 标签发生冲突;自定义组件请用大驼峰形式命名,区别于 UI 库

BAD

html
<!-- 自定义组件 -->
<item />
<!-- 自定义组件 -->
<list-item />
1
2
3
4

GOOD

html
<!-- 大驼峰形式 -->
<ListItem />
<!-- 大驼峰形式 -->
<TodoItem />

<!-- 区别于element -->
<el-form></el-form>
1
2
3
4
5
6
7
  • 👉 在组件接收的属性中,属性定义应该尽可能详细,至少指定类型

BAD

js
props: ["status"];
1

GOOD

js
props: {
  status: {
    type: String;
  }
}
1
2
3
4
5

EVEN BETTER 💯

js
props: {
  status: {
    type: String,
    required: true,

    validator: value => {
      return [
        'syncing',
        'synced',
        'version-conflict',
        'error'
      ].includes(value)
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

BAD

js
<ul>
  <li
    v-for="user in users"
    v-if="user.isActive"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>

1
2
3
4
5
6
7
8
9
10

GOOD

js
<ul>
  <template v-for="user in users" :key="user.id">
    <li v-if="user.isActive">
      {{ user.name }}
    </li>
  </template>
</ul>
1
2
3
4
5
6
7

JS 规范

  • 👉 使用 async await 语法糖进行异步转同步任务,减少代码量

BAD

js
intData() {
  getDetail({
    dictCode: 'FIRE_PLUG_STATUS ',
  }).then(res => {
    const data = res.data;
  })
}
1
2
3
4
5
6
7

GOOD

js
async intData() {
  const { data } = await getDetail({
    dictCode: 'FIRE_PLUG_STATUS ',
  })
}
1
2
3
4
5
  • 👉 合理使用 JS 数组 API

BAD

js
data.map((item) => {
  if (item.id) {
    ...
  } else {
    ...
  }
  return item;
});
1
2
3
4
5
6
7
8

GOOD

js
data.forEach((item) => {
  if (item.id) {
    ...
  } else {
    ...
  }
});
1
2
3
4
5
6
7
  • 👉 能使用 ES6 语法的地方,尽量使用 ES6 语法

BAD

js
arr.forEach((item) => {
  if (item.id) {
    this.form.name = item.name;
    this.form.age = item.age;
    this.form.address = item.address;
  }
});
1
2
3
4
5
6
7

GOOD

js
arr.forEach((item) => {
  const { id, name, age, address } = item;
  if (id) Object.assign(this.form, { name, age, address });
});
1
2
3
4