Play with code | Share some practical Vue front-end code (1)

Table of contents

1. Naming convention

1.1 Project file naming

1.1.1 Project name

1.1.2 Directory name

1.1.3 Image file name

1.1.4 HTML file name

1.2 Vue component naming

1.2.1 Single file component name

1.2.2 Singleton component name

1.2.3 Basic component name

1.2.4 Business components

1.2.5 Tightly coupled component names

1.2.6 Word order in component names

1.2.7 Complete word component name

1.3 Code parameter naming

1.3.1 name

1.3.3 router

1.3.4 Components in templates

1.3.5 Self-closing components

1.3.6 Variables

1.3.7 Constants

1.3.8 Method

1.3.9 Custom events

1.3.10 Event methods


1. Naming convention

Commonly used naming conventions on the market:

  • camelCase(CamelCase nomenclature - first letter lowercase)
  • PascalCase(CamelCase nomenclature - capitalize the first letter)
  • kebab-case(Short horizontal line connection type)
  • Snake(Underlined connection type)

1.1 Project file naming

1.1.1 Project name

All in lowercase, separated by dashes . Example: my-project-name.

1.1.2 Directory name

According to the project naming rules, when there is a plural structure, the plural naming method should be used . Examples: docs, assets, components, directives, mixins, utils, views.

my-project-name/
|- BuildScript    // 流水线部署文件目录
|- docs           // 项目的细化文档目录(可选)
|- nginx          // 部署在容器上前端项目 nginx 代理文件目录
|- node_modules   // 下载的依赖包
|- public         // 静态页面目录
    |- index.html // 项目入口
|- src            // 源码目录
    |- api        // http 请求目录
    |- assets     // 静态资源目录,这里的资源会被wabpack构建
        |- icon   // icon 存放目录
        |- img    // 图片存放目录
        |- js     // 公共 js 文件目录
        |- scss   // 公共样式 scss 存放目录
            |- frame.scss   // 入口文件
            |- global.scss  // 公共样式
            |- reset.scss   // 重置样式
    |- components     // 组件
    |- plugins        // 插件
    |- router         // 路由
    |- routes         // 详细的路由拆分目录(可选)
        |- index.js
    |- store          // 全局状态管理
    |- utils          // 工具存放目录
        |- request.js // 公共请求工具
    |- views          // 页面存放目录
    |- App.vue        // 根组件
    |- main.js        // 入口文件
    |- tests          // 测试用例
    |- .browserslistrc// 浏览器兼容配置文件
    |- .editorconfig  // 编辑器配置文件
    |- .eslintignore  // eslint 忽略规则
    |- .eslintrc.js   // eslint 规则
    |- .gitignore     // git 忽略规则
    |- babel.config.js // babel 规则
    |- Dockerfile // Docker 部署文件
    |- jest.config.js
    |- package-lock.json
    |- package.json // 依赖
    |- README.md // 项目 README
    |- vue.config.js // webpack 配置

1.1.3 Image file name

All are in lowercase, single word names are preferred, and multiple word names are separated by underscores .

banner_sina.gif
menu_aboutus.gif
menutitle_news.gif
logo_police.gif
logo_national.gif
pic_people.jpg
pic_TV.jpg

1.1.4 HTML file name

All are in lowercase, single word names are preferred, and multiple word names are separated by underscores .

|- error_report.html
|- success_report.html

1.1.5 CSS file name

All are in lowercase, single word names are preferred, and multiple word names are separated by dashes .

|- normalize.less
|- base.less
|- date-picker.scss
|- input-number.scss

1.1.6 JavaScript file name

All are in lowercase, single word names are preferred, and multiple word names are separated by dashes .

|- index.js
|- plugin.js
|- util.js
|- date-util.js
|- account-model.js
|- collapse-transition.js

The above rules can be quickly remembered as "underline for static files and dash for compiled files".



1.2 Vue component naming

1.2.1 Single file component name

The file extension is  .vue (  single-file components single file component). Single-file component names should always start with a capital letter  (PascalCase).

components/
|- MyComponent.vue

1.2.2 Singleton component name

Components that only have a single active instance should be named with  The a prefix to indicate uniqueness.

This does not mean that the component can only be used on a single page, but only once per page . These components never accept any props because they are customized for your application. If you find it necessary to add props, it indicates that this is actually a reusable component, but is currently only used once per page.

For example, the header and sidebar components are used on almost every page and do not accept props. This component is customized specifically for the application.

components/
|- TheHeading.vue
|- TheSidebar.vue

1.2.3 Basic component name

Basic components: Basic components that do not include business, independent, and specific functions, such as date pickers , modal boxes , etc. As the basic controls of the project, this type of component will be used extensively. Therefore, the API of the component is highly abstracted and can achieve different functions through different configurations.

Basic components that apply specific styles and conventions (that is, components that are presentational, non-logic or stateless, and do not contain business logic) should all start with a specific prefix - Base. Basic components can be used multiple times in one page and can also be reused in different pages. They are highly reusable components.

components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue

1.2.4 Business components

Business component: It is not like the basic component that only contains a certain function, but is reused by multiple pages in the business (with reusability). The difference between it and the basic component is that the business component will only be used in the current project. Used, it is not universal, and will contain some businesses, such as data requests; while the basic component does not contain businesses and can be used in any project, with a single function, such as an input box with data verification function.

Components that are mixed with complex business (have their own  data, prop related processing), that is, business components should be  Custom named with the prefix. Business components are in a page. For example: there is a card list in a certain page, and cards whose style and logic are closely related to the business are business components.

components/
|- CustomCard.vue

1.2.5 Tightly coupled component names

Child components that are tightly coupled to a parent component should be named with the parent component name as a prefix.  Because editors usually organize files alphabetically, doing this will keep related files together.

components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue

1.2.6 Word order in component names

Component names should start with a high-level (usually descriptive) word and end with a descriptive modifier.  Because the editor usually organizes files in alphabetical order, important relationships between components are now clear. The following components are mainly used for search and setting functions.

components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue

There is another multi-level directory method, which is to put all search components in the "search" directory and all setting components in the "settings" directory. We only recommend doing this for very large applications (e.g. 100+ components), as searching through multiple levels of directories takes more effort than scrolling through a single components directory.

1.2.7 Complete word component name

Component names should be preferred rather than abbreviated.  Autocompletion in editors has made writing long names very cheap, and the clarity it brings is invaluable. Uncommon abbreviations should especially be avoided.

components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue

1.3 Code parameter naming

1.3.1 name

Component names should always be multiple words and should always be PascalCase.  Except for the root component App and  <transition>Vue <component> built-in components such as . Doing so avoids conflicts with existing and future HTML elements, since all HTML element names are single words.

export default {
  name: 'ToDoList',
  // ...
}

1.3.2 prop

Props should always be named using camelCase when declaring them, and kebab-case should always be used in templates and JSX . We simply follow the conventions of each language, and the more natural one in JavaScript is camelCase. In HTML it is kebab-case.

<WelcomeMessage greeting-text="hi"/>
export default {
  name: 'MyComponent',
  // ...
  props: {
    greetingText: {
      type: String,
      required: true,
      validator: function (value) {
        return ['syncing', 'synced',].indexOf(value) !== -1
      }
    }
  }
}

 

1.3.3 router

Vue Router Path naming adopts kebab-case format.  Words using Snake (such as: /user_info) or camelCase (such as: /userInfo) will be treated as one word, and search engines cannot distinguish semantics.

// bad
{
  path: '/user_info', // user_info 当成一个单词
  name: 'UserInfo',
  component: UserInfo,
  meta: {
    title: ' - 用户',
    desc: ''
  }
},

// good
{
  path: '/user-info', // 能解析成 user info
  name: 'UserInfo',
  component: UserInfo,
  meta: {
    title: ' - 用户',
    desc: ''
  }
},

1.3.4 Components in templates

For most projects, component names should always be PascalCase in single-file components and string templates, but always kebab-case in DOM templates.

<!-- 在单文件组件和字符串模板中 --> 
<MyComponent/>

<!-- 在 DOM 模板中 --> 
<my-component></my-component>

1.3.5 Self-closing components

Components without content should be self-closing in single-file components, string templates, and JSX - but never do this in DOM templates.

<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>

<!-- 在所有地方 -->
<my-component></my-component>

1.3.6 Variables

  • Naming method: camelCase
  • Naming convention: type + method of object description or attributes
  • // bad
    var getTitle = "LoginTable"
    
    // good
    let tableTitle = "LoginTable"
    let mySchool = "我的学校"

1.3.7 Constants

  • Naming method: all capital letters separated by underscores
  • Naming convention: Use capital letters and underscores to combine names, and underscores are used to separate words.
const MAX_COUNT = 10
const URL = 'http://test.host.com'

1.3.8 Method

  • Naming method: camelCase
  • Naming convention: uniformly use verb or verb + noun form
// 1、普通情况下,使用动词 + 名词形式
// bad
go、nextPage、show、open、login

// good
jumpPage、openCarInfoDialog

// 2、请求数据方法,以 data 结尾
// bad
takeData、confirmData、getList、postForm

// good
getListData、postFormData

// 3、单个动词的情况
init、refresh

1.3.9 Custom events

Custom events should always use kebab-case event names.

Unlike components and props, there is no automatic case conversion for event names. Instead, the name of the triggered event needs to exactly match the name used to listen for this event.

this.$emit('my-event')
<MyComponent @my-event="handleDoSomething" />

Unlike components and props, the event name is not used as a JavaScript variable or property name, so there is no reason to use camelCase or PascalCase. And  v-on the event listener will be automatically converted to all lowercase in the DOM template (because HTML is case-insensitive), so it  v-on:myEvent will become  v-on:myevent- making it  myEvent impossible to be monitored.

From the native events, you can find how to use them as follows:

<div
  @blur="toggleHeaderFocus"
  @focus="toggleHeaderFocus"
  @click="toggleMenu"
  @keydown.esc="handleKeydown"
  @keydown.enter="handleKeydown"
  @keydown.up.prevent="handleKeydown"
  @keydown.down.prevent="handleKeydown"
  @keydown.tab="handleKeydown"
  @keydown.delete="handleKeydown"
  @mouseenter="hasMouseHoverHead = true"
  @mouseleave="hasMouseHoverHead = false">
</div>

In order to distinguish the use of native events and custom events in Vue, it is recommended that in addition to using kebab-case for multi-word event names, the naming must also follow  the form of on + verb  , as follows:

<!-- 父组件 -->
<div
  @on-search="handleSearch"
  @on-clear="handleClear"
  @on-clickoutside="handleClickOutside">
</div>

 

// 子组件
export default {
  methods: {
    handleTriggerItem () {
      this.$emit('on-clear')
    }
  }
}

1.3.10 Event methods

  • Naming method: camelCase
  • Naming convention: handle + name (optional) + verb
<template>
  <div
    @click.native.stop="handleItemClick()"
    @mouseenter.native.stop="handleItemHover()">
  </div>
</template>

<script>

export default {
  methods: {
    handleItemClick () {
      //...
    },
    handleItemHover () {
      //...
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/qq_22903531/article/details/132595180