Vue3 front-end code writing specification

Introduction
If the development team is only one person, then the code written by oneself is the norm. With the expansion of the company's business, the team continues to grow, and it is time to start thinking about collaboration and coding norms.

One person can go faster, and a group of people can go farther. The premise is a unified strategy and continuous optimization.

0. Semantic

Semanticization of component names, variable names, constant names, etc., facilitates collaboration and improves efficiency

Components:

  • Folder Name: Uppercase CamelCase TestList
  • File name: uppercase camelCase TestList.vue

variable, constant name

Semantic

Variable: lowercase camelCase

 let infoList = ' '

Constant: uppercase

const MAX_NUMBER = 10

1. Single file component reference

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

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

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

2. Single-file attribute declaration order

<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. Custom events

  • It is recommended to use on-verb name for custom event name
  • It is recommended to use handle+verb name for event processing function
// 例子:
this.$emit('on-change')

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

4. Variables

let test = 10

5. Constants

const MAX_TEST = 10

6. Mixed quotation marks

  • html recommends using double quotes " "
  • js suggests using single quotes ' '
let str = 'jack'

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

7. Use when multiple attributes

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

8. Component style declarations set the scope as much as possible

Due to component development, style naming conflicts are easy

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

9. Notes

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

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

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

10. Style penetration

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

11. Redundant code

Remove the console.log debugger from the page before submitting the code

12 interface type

prefixed with an uppercase 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 cases

<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>

Guess you like

Origin blog.csdn.net/weixin_42901443/article/details/129143643