命名规范

77 阅读2分钟

前言

为什么会需要命名规范这种事情,究其原因是为了保持代码风格统一,要是名字都写的五花八门的,看起来会很奇怪。

文章目的

本文将带你学习命名有哪些规范,在 vue 和 react或者 Ts 中各个情况下又需要遵守哪一种规范。

命名规范有哪些

首先,我们得知道我们有哪些可用的命名规范,又是在什么情况下使用

PascalCase

帕斯卡命名法,俗称大驼峰,一般用在组件命名上

camelCase

小驼峰,常用在变量命名上

kebab-case

短横线连接,常用在属性上或者文件路径中


了解到我们常用的这几种规范后,下面我们开始讲不同的框架中各个场景使用的命名规范

vue

PascalCase

PascalCase通常应用在单文件组件命名上,这样能很好的区分哪些是单文件组件,哪些是原生组件。

<script setup lang="ts">
import Test from "./Test.vue";

</script>

<template>
  <div>
    <Test/>  <!-- Vue组件 -->
    <input/> <!-- HTML原生标签 -->
  </div>
</template>

camelCase

camelCase则是通常应用在变量上以及接受 props 时和Hooks和函数命名上,这种命名法便于阅读和理解其意义,

<script setup lang="ts">
import Test from "./Test.vue";
import { ref } from "vue";
import { useMouse } from './useMouse'

const { x, y } = useMouse() //camelCase
defineProps({
  propelNum: { //camelCase
    type: String
  }
})
//camelCase
const myMsg = ref<string | undefined>('msg')
//camelCase
const updateMsg = (input?: string) => {
  myMsg.value = input
}

</script>

<template>
  <div>
    <div>{{ propelNum }}</div>
    <div>{{ x, y }}</div>
    <Test @update-msg="updateMsg" />
  </div>
</template>

kebab-case

在 vue 模板中使用组件时需要使用,例如


import MyComponent from './components/MyComponent.vue';

export default {
  components: {
    MyComponent
  }
};

// 在模板中使用组件时
<template>
  <my-component></my-component>   //kebab-case
</template>

文件或者文件夹命名时也可以使用 kebab-case 方式,因为不同操作系统会有大小写敏感性问题,导致 git 识别不出来。

在 日常编写vue 中呢,主要是属性和事件中使用

<script setup lang="ts">
import Test from "./Test.vue";
import { ref } from "vue";

const myMsg = ref<string | undefined>('msg')

const updateMsg = (input?: string) => {
  myMsg.value = input
}

</script>

<template>
    <Test 
    @update-msg="updateMsg" //camelCase
    :my-msg="myMsg"
  />
</template>

vue 的就到此结束了哈,接下来开始 react

react

PascalCase

日常在组件命名上使用,可以便捷区分组件和原生组件。

import './App.css';
import Header from './Header';

function App() {
  return (
    <div className="App">
      <Header />
      <header>111</header>
    </div>
  );
}

export default App;


camelCase

camelCase在react 的场景就比较多了,有HOC高阶组件,事件绑定,定义state,props还有 useHooks 的场景,都是使用camelCase

import { useRef, useState } from 'react';
import './App.css';
import withAuth from './Auth';
import Header from './Header';
interface Props {
  msg: "msg"
}
function App(props: Props) {
  const [inputValue, setInputValue] = useState<string>('')
  const inputRef = useRef<HTMLInputElement>(null)
  const inputValueChange = (event) => setInputValue(event.target.value)
  return (
    <div className="App">
      <Header />
      <div>{props.msg}</div>
      <input ref={inputRef} value={inputValue} onChange={inputValueChange} />
    </div>
  );
}

export default withAuth(App);





好啦,今天的文章先到此结束