vue3 前端代码书写规范

引言
如果开发团队就一个人的话,那么自己写的代码就是规范,随着公司业务的扩展,团队不断壮大,这时候就要开始考虑协作和编码规范问题了。

一个人走的更快,一群人可以走的更远,前提是统一的策略,还要不断地优化。

0.语义化

组件名、变量名、常量名等等语义化,便于协作,提高效率

组件:

  • 文件夹名:大写驼峰 TestList
  • 文件名:大写驼峰TestList.vue

变量、常量名

语义化

变量:小写驼峰

 let infoList = ' '

常量:大写

const MAX_NUMBER = 10

1.单文件组件引用

<template>
     <!-- 组件内没有内容 -->
     <test-component/>

     <!-- 组件标签之间有内容 -->
     <container-component>This is content~</container-component>
</template>

<script>
   // 使用驼峰命令
    import TestComponent  from './components/TestComponent.vue'
</script>

2. 单文件属性声明顺序

<script lang="ts" setup name="componentName">
onBeforeMount(() => {
  console.log('onBeforeMount')
})

onMounted(() => {
  console.log('onMounted')
})

onBeforeUpdate(() => {
  console.log('onBeforeUpdate')
})

onUpdated(() => {
  console.log('onUpdated')
})

onBeforeUnmount(() => {
  console.log('onBeforeUnmount')
})

onUnmounted(() => {
  console.log('onUnmounted')
})
</script>

3.自定义事件

  • 自定义事件名建议用 on-动词名
  • 事件处理函数建议用 handle+动词名
// 例子:
this.$emit('on-change')

<my-component @on-change='handleChange'/>

4.变量

let test = 10

5.常量

const MAX_TEST = 10

6.引号混用

  • html建议用双引号 " "
  • js建议用单引号 ’ ’
let str = 'jack'

 <test-component data-attributes="test" />

7.多个属性时采用

<li
   :span="4"
    style="margin-bottom: 10px"
    v-for="(item, index) in testList"
    :key="index"
>
    {
   
   {item.name}}
</li>

8.组件样式声明尽可能设置作用域

由于组件化开发很容易样式命名冲突

<style scoped lang="less">
.test-list {
 //...
}
.test-list .test-item{
 //...
}
</style>

9.注释

 <!-- 序号 -->  
 <el-table-column prop="id" label="序号" />

 <!-- 名称 -->
 <el-table-column prop="name" label="名称" />
// 删除
const delete = (row: string) => {
   //...
}

// 增加
const add = (row: string) => {
   //...
}

10.样式穿透

:deep(.el-card__body) {
  //...
}

11.冗余代码

提交代码前移除页面中的 console.log debugger

12 接口类型

以大写 I 为前缀

export interface IState {
	roleList: Object;
	restartVisible: boolean;
	sid: string;
	dialogVisible: boolean;
	loading: boolean;
	list: IDevmemt[];
	total: number;
	listQuery: IListQuery;
	name:string
}

export interface IStateParams extends IState {
  id: string;
}

13 案例

<template>
  <div>
    <el-card shadow="hover">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <!-- 名称 -->
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>

        <!-- 标签 -->
        <el-form-item label="标签" prop="label">
          <el-link type="primary" @click="addFruitConfig"> +添加一行 </el-link>
          <span>(最多20个标签)</span>
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="描述" prop="describe">
          <el-input v-model="ruleForm.describe" :rows="2" type="textarea" placeholder="请输入描述" />
        </el-form-item>

        <!-- 确定 取消 -->
        <div class="btn-flex">
          <div class="box"></div>
          <div class="box1">
            <el-button type="primary"> 取消 </el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { activationApi } from '/@/api/devmgmt'
import { useRoute } from 'vue-router'

const Route = useRoute()
const uuid = Route.query.uuid
const type = Route.query.type

const router = useRouter()

const downloadDisabled = ref(false)
const downloadText = ref()
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: '',
  label: [
    {
      label: ''
    }
  ],
  longitude: '',
  latitude: '',
  address: '',
  describe: ''
})

// 输入校验
const validateName = (rule: any, value: string, callback: any) => {
  if (ruleForm.name != '') {
    downloadDisabled.value = true
  } else {
    downloadDisabled.value = false
  }
  callback()
}

// 必填
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    {
      validator: validateName,
      trigger: 'change'
    }
  ]
})

// 新增
const addFruitConfig = () => {
  ruleForm.label.push({
    label: ''
  })
}

// 删除
const removeFruitConfig = (item: any) => {
  const index = ruleForm.label.indexOf(item)
  if (index !== -1) {
    ruleForm.label.splice(index, 1)
  }
}

// 确定
const submitForm = async (formEl: FormInstance | undefined) => {
  let label: any = []
  ruleForm.label.forEach((item: any) => {
    let ary = Object.values(item)
    label.push(...ary)
  })
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      const params = {
        sid: uuid,
        name: ruleForm.name,
        type: type,
        address: ruleForm.address,
        longitude: parseFloat(ruleForm.longitude),
        latitude: parseFloat(ruleForm.latitude),
        detail: ruleForm.describe,
        label: label
      }
      activationApi(params).then((res: any) => {})
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped lang="scss">
.width120 {
  width: 120px;
}
.latitude-text .width300 {
  width: 300px;
  margin: 0 10px 0 22px;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_42901443/article/details/129143643