vue前端开发规范

命名编码规范

驼峰式命名法介绍

-Pascal Case 大驼峰式命名法:首字母大写。eg:StudentInfo、UserInfo、ProductInfo
-Camel Case 小驼峰式命名法:首字母小写。eg:studentInfo、userInfo、productInfo

文件命名

文件名不能含有空格
文件名建议只使用小写字母,不使用大写字母。(但比如说像github的说明类文件,README,则应该全部使用大写)
文件名包含多个单词时,单词之间建议使用半角的连词线 ( - ) 分隔。

// 反例
├── index.html
├── main.js
└── components
    ├── pageheader
    ├── pagearticle
    └── pageheader

// 正例
├── index.html
├── main.js
└── components
    ├── page-header
    ├── page-article
    └── page-header

命名规范

es6提供了两个新的变量命名关键字,const,let。加上var,一共3个命名关键字。

怎么用这个三个关键字

当你的变量能保证不会被修改,则用const,如一些常量等
如果是会一直修改,则使用let
尽量不要使用var

变量

变量命名:
-命名方式:小驼峰式命名方法
-命名规范:类型+对象描述的方式,如果没有明确的类型,就可以使前缀为名词

javascript变量命名类型 变量命名前缀
array数组 a
boolean布尔值 b
float浮点数 l
function 函数 fn
int 整型 i
object 对象 o
regular 正则 r
string 字符串 s
var aName = [1, 2, 3];
var oBtn = document.getElementById('btn');
function fnName(){};
var iCount = 0;
var sName = "zhuyujia";

函数

命名方式:小驼峰方式 ( 构造函数使用大驼峰命名法 )
命名规则:前缀为动词

动词 含义 返回值
can 判断是否可执行某个动作 ( 权限 ) 函数返回一个布尔值 true:可执行;false:不可执行
has 判断是否含有某个值 函数返回一个布尔值 true:含有此值;false:不含有此值
is 判断是否为某个值 函数返回一个布尔值 true:为某个值;false:不为某个值
get 获取某个值 函数返回一个非布尔值
set 设置某个值 无返回值、返回是否设置成功或者返回链式对象
//是否可阅读
function canRead() {
    return true;
}
//获取姓名
function getName {
    return this.name;
}

常量

-命名方式:全部大写
-命名规范:使用大写字母和下划线来组合命名,下划线用以分割单词

var MAX_COUNT = 10;
var URL = 'http://www.baidu.com';

类的成员

-公共属性和方法:同变量命名方式
-私有属性和方法:前缀为下划线(_)后面跟公共属性和方法一样的命名方式

function Student(name) {
    var _name = name;  // 私有成员

    // 公共方法
    this.getName = function() {
        return _name;
    }

    // 公共方式
    this.setName = function(value) {
        _name = value;
    }
}
var st = new Student('tom');
st.setName('jerry');
console.log(st.getName()); // => jerry:输出_name私有变量的值

注释规范

单行注释

-单独一行://(双斜线)与注释文字之间保留一个空格
-在代码后面添加注释://(双斜线)与代码之间保留一个空格,并且//(双斜线)与注释文字之间保留一个空格。
-注释代码://(双斜线)与代码之间保留一个空格。

// 调用了一个函数;1)单独在一行
setTitle();
var maxCount = 10; // 设置最大量;2)在代码后面注释
// setName(); // 3)注释代码

多行注释( / 注释说明 /)

-若开始(/* 和结束 / )都在一行,推荐采用单行注释
-若至少三行注释时,第一行为/
,最后行为/,其他行以开始,并且注释文字与*保留一个空格。

/*
 * 代码执行到这里后会调用setTitle()函数
 * setTitle():设置title的值
 */
setTitle();

函数(方法)注释

-函数(方法)注释也是多行注释的一种,但是包含了特殊的注释要求,参照 javadoc(百度百科)

/** 
 * 函数说明 
 * @关键字 
 */
注释名 语法 含义 示例
@param @param参数名 {参数类型} 描述信息 描述参数的信息 @param name {String} 传入名称
@return @return{返回类型} 描述信息 描述返回值的信息 @return {Boolean} true:可执行;false:不可执行
@author @author作者信息 [附属信息:如邮箱、日期] 描述此函数作者的信息 @author张三 2019/06/01
@version @versionXX.XX.XX 描述此函数的版本号 @version 1.03
@example @example示例代码 @example setTitle('测试') 如下
/**
 - 合并Grid的行
 - [@param](/user/param) grid {Ext.Grid.Panel} 需要合并的Grid
 - [@param](/user/param) cols {Array} 需要合并列的Index(序号)数组;从0开始计数,序号也包含。
 - [@param](/user/param) isAllSome {Boolean} :是否2个tr的cols必须完成一样才能进行合并。true:完全一样;false(默认):不完全一样
 - [@return](/user/return) void
 - [@author](/user/author) polk6 2019/06/01
 - [@example](/user/example)
 - _________________                             _________________
 - |  年龄 |  姓名 |                             |  年龄 |  姓名 |
 - -----------------      mergeCells(grid,[0])   -----------------
 - |  18   |  张三 |              =>             |       |  张三 |
 - -----------------                             -  18   ---------
 - |  18   |  王五 |                             |       |  王五 |
 - -----------------                             -----------------
*/
function mergeCells(grid, cols, isAllSome) {
    // Do Something
}

关于VUE的开发规范

下面是vue的生命钩子

vue2.0 Description
beforeCreate 组件实例刚刚被创建,组件属性计算之前,如data属性等
created 组件实例创建完成,属性已绑定,但DOM还未生成,$el属性还不存在
beforeMount 模板编译/挂载之前
mounted 模板编译/挂载之后
beforeUpdate 组件更新之前
updated 组件更新之后
activated for \color{red}{keep-alive},组件被激活时调用
deactivated for \color{red}{keep-alive},组件被移除时调用
beforeDestory 组件销毁前调用
destoryed 组件销毁后调用

vue文件基本结构

  <template>
          <div>
            <!--必须在div中编写页面-->
          </div>
        </template>
        <script>
          export default {
            components : {},//5.注册需要用到的组件
            props:{},//7.传递到本组件的props
            data () {//8.组件的 data 必须是一个函数
              return {
              }
            },
            computed:{},//8
            watch:{},//9
            //所有的钩子函数:如created
            created(){},//9
            methods: {//10
            },
         }
        </script>
        <!--声明语言,并且添加scoped-->
        <style lang="scss" scoped>
        </style>

vue文件方法声明顺序

1.副作用 (触发组件外的影响)
--el
2.全局感知 (要求组件以外的知识)
--name
--parent
3.组件类型 (更改组件的类型)
--functional
4.模板修改器 (改变模板的编译方式)
--delimiters
--comments
5.模板依赖 (模板内使用的资源)
--components
--directives
--filters
6.组合 (向选项里合并属性)
--extends
--mixins
7.接口 (组件的接口)
--inheritAttrs
--model
--props/propsData
8.本地状态 (本地的响应式属性)
--data
--computed
9.事件 (通过响应式事件触发的回调)
--watch
生命钩子函数
---beforeCreate
---created
---beforeMount
---mounted
---beforeUpdate
---updated
---activated
---deactivated
---beforeDestroy
---destroyed
10.非响应式的属性 (不依赖响应系统的实例属性)
--methods
11.渲染 (组件输出的声明式描述)
--template/render
--renderError

元素特性的顺序

- v-for
- v-if / v-show
- id
- ref / key / slot
- v-model
- v-on//强烈建议用简写 @,如@change

单文件组件,顶级元素的顺序

<template>
<script>
<style>

按照这个顺序组织代码就可以。注意style只能在最下面,script和template至少要有一个

对象Objects

1.1使用字面量语法创建对象。

// bad
const item = new Object();
 
// good
const item = {};

1.2.当创建带有动态属性名称的对象时使用计算的属性名称。

function getKey(k) {
    return `a key named ${k}`;
}
 
// bad
const obj = {
    id: 5,
    name: 'San Francisco',
};
obj[getKey('enabled')] = true;
 
// good
const obj = {
    id: 5,
    name: 'San Francisco',
    [getKey('enabled')]: true,
};

1.3.使用对象方法速记语法。

// bad
const atom = {
    value: 1,
 
    addValue: function (value) {
    return atom.value + value;
    },
};
 
// good
const atom = {
    value: 1,
 
    addValue(value) {
    return atom.value + value;
    },
};

1.4.使用对象属性速记语法。

const lukeSkywalker = 'Luke Skywalker';
 
// bad
const obj = {
    lukeSkywalker: lukeSkywalker,
};
 
// good
const obj = {
    lukeSkywalker,
};

1.5.将速记属性分组写在对象声明的开始处。

const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
 
// bad
const obj = {
    episodeOne: 1,
    twoJediWalkIntoACantina: 2,
    lukeSkywalker,
    episodeThree: 3,
    mayTheFourth: 4,
    anakinSkywalker,
};
 
// good
const obj = {
    lukeSkywalker,
    anakinSkywalker,
    episodeOne: 1,
    twoJediWalkIntoACantina: 2,
    episodeThree: 3,
    mayTheFourth: 4,
};

1.6.只用引号引无效标识符的属性。

// bad
const bad = {
    'foo': 3,
    'bar': 4,
    'data-blah': 5,
};
 
// good
const good = {
    foo: 3,
    bar: 4,
    'data-blah': 5,
};

1.7.不要直接调用 Object.prototype 的方法,比如 hasOwnProperty, propertyIsEnumerable, 和 isPrototypeOf.

// bad
console.log(object.hasOwnProperty(key));
 
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
 
// best
const has = Object.prototype.hasOwnProperty; // 在模块作用域内,缓存查找一次。
/* or */
import has from 'has';
// ...
console.log(has.call(object, key));

1.8用对象展开操作符浅复制对象,优先于Object.assign 。使用对象剩余操作符来获得一个省略某些属性的新对象。

// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); //  `original` 是可变的 ?_?
delete copy.a; // so does this
 
// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
 
// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
 
const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

数组Arrays

2.1使用字面量创建数组

// bad
const items = new Array();
 
// good
const items = [];

2.2在向数组添加元素时使用push代替直接赋值。

const someStack = [];
 
// bad
someStack[someStack.length] = 'abracadabra';
 
// good
someStack.push('abracadabra');

2.3使用数组展开操作符 ... 复制数组。

// bad
const len = items.length;
const itemsCopy = [];
let i;
 
for (i = 0; i < len; i += 1) {
    itemsCopy[i] = items[i];
}
 
// good
const itemsCopy = [...items];

2.4使用展开操作符 ... 代替 Array.from,来将一个类数组(array-like) 对象转换成数组。

const foo = document.querySelectorAll('.foo');
 
// good
const nodes = Array.from(foo);
 
// best
const nodes = [...foo];

2.5实用 Array.from 代替展开操作符 ... 来映射迭代,因为它避免了创建媒介数组。

// bad
const baz = [...foo].map(bar);
 
// good
const baz = Array.from(foo, bar);

2.6在数组方法回调中使用 return 语句。如果函数体由一个返回无副作用的表达式的单个语句组成,那么可以省略返回值

// good
[1, 2, 3].map((x) => {
    const y = x + 1;
    return x * y;
});
 
// good
[1, 2, 3].map(x => x + 1);
 
// bad - 没有返回值意味着  `memo` 在第一次迭代后变成 undefined
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
    const flatten = memo.concat(item);
    memo[index] = flatten;
});
 
// good
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
    const flatten = memo.concat(item);
    memo[index] = flatten;
    return flatten;
});
 
// bad
inbox.filter((msg) => {
    const { subject, author } = msg;
    if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
    } else {
    return false;
    }
});
 
// good
inbox.filter((msg) => {
    const { subject, author } = msg;
    if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
    }
 
    return false;
});

2.7如果数组有多行,请在打开和关闭数组括号之前使用换行符。

// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
 
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
 
const numberInArray = [
1, 2,
];
 
// good
const arr = [[0, 1], [2, 3], [4, 5]];
 
const objectInArray = [
{
    id: 1,
},
{
    id: 2,
},
];
 
const numberInArray = [
1,
2,
];

解构 Destructuring

3.1当访问和使用对象的多个属性时,请使用对象解构

// bad
function getFullName(user) {
    const firstName = user.firstName;
    const lastName = user.lastName;
 
    return `${firstName} ${lastName}`;
}
 
// good
function getFullName(user) {
    const { firstName, lastName } = user;
    return `${firstName} ${lastName}`;
}
 
// best
function getFullName({ firstName, lastName }) {
    return `${firstName} ${lastName}`;
}

3.2使用数组解构

const arr = [1, 2, 3, 4];
 
// bad
const first = arr[0];
const second = arr[1];
 
// good
const [first, second] = arr;

3.3使用对象解构来实现多个返回值,而不是数组解构

// bad
function processInput(input) {
    // 那么奇迹发生了
    return [left, right, top, bottom];
}
 
// 调用者需要考虑返回数据的顺序
const [left, __, top] = processInput(input);
 
// good
function processInput(input) {
    // 那么奇迹发生了
    return { left, right, top, bottom };
}
 
// 调用者只选择他们需要的数据
const { left, top } = processInput(input);

字符串 Strings

4.1字符串使用单引号 ''。

// bad
const name = "Capt. Janeway";
 
// bad - 模板字面量应该包含插值或换行符
const name = `Capt. Janeway`;
 
// good
const name = 'Capt. Janeway';

4.2超过100个字符,导致换行的字符串不应使用字符串连接符写成多行。

// bad
const errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';
 
// bad
const errorMessage = 'This is a super long error that was thrown because ' +
    'of Batman. When you stop to think about how Batman had anything to do ' +
    'with this, you would get nowhere fast.';
 
// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

4.3以编程方式构建字符串时,请使用模板字符串而不是字符串连接。

// bad
function sayHi(name) {
    return 'How are you, ' + name + '?';
}
 
// bad
function sayHi(name) {
    return ['How are you, ', name, '?'].join();
}
 
// bad
function sayHi(name) {
    return `How are you, ${ name }?`;
}
 
// good
function sayHi(name) {
    return `How are you, ${name}?`;
}

4.4永远不要在字符串上使用 eval() ,它会打开太多的漏洞
4.5不要转义字符串中不必要转义的字符

// bad
const foo = '\'this\' \i\s \"quoted\"';
 
// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;

箭头函数 Arrow Functions

5.1当您必须使用匿名函数(如在传递一个内联回调时),请使用箭头函数表示法

// bad
[1, 2, 3].map(function (x) {
    const y = x + 1;
    return x * y;
});
 
// good
[1, 2, 3].map((x) => {
    const y = x + 1;
    return x * y;
});

5.2如果函数体由一个返回无副作用(side effect)的expression(表达式)的单行语句组成,那么可以省略大括号并使用隐式返回。否则,保留大括号并使用 return 语句

// bad
[1, 2, 3].map(number => {
    const nextNumber = number + 1;
    `A string containing the ${nextNumber}.`;
});
 
// good
[1, 2, 3].map(number => `A string containing the ${number}.`);
 
// good
[1, 2, 3].map((number) => {
    const nextNumber = number + 1;
    return `A string containing the ${nextNumber}.`;
});
 
// good
[1, 2, 3].map((number, index) => ({
    [index]: number,
}));
 
// No implicit return with side effects
function foo(callback) {
    const val = callback();
    if (val === true) {
    // Do something if callback returns true
    }
}
 
let bool = false;
 
// bad
foo(() => bool = true);
 
// good
foo(() => {
    bool = true;
});

5.3如果表达式跨多行,将其包裹在括号中,可以提高可读性。

// bad
['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
    )
);
 
// good
['get', 'post', 'put'].map(httpMethod => (
    Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
    )
));

5.4如果你的函数只有一个参数并且不使用大括号,则可以省略参数括号。否则,为了清晰和一致性,总是给参数加上括号。

// bad
[1, 2, 3].map((x) => x * x);
 
// good
[1, 2, 3].map(x => x * x);
 
// good
[1, 2, 3].map(number => (
    `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
));
 
// bad
[1, 2, 3].map(x => {
    const y = x + 1;
    return x * y;
});
 
// good
[1, 2, 3].map((x) => {
    const y = x + 1;
    return x * y;
});

5.5避免使用比较运算符(< =, >=)时,混淆箭头函数语法(=>)。

// bad
const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
 
// bad
const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
 
// good
const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
 
// good
const itemHeight = (item) => {
    const { height, largeSize, smallSize } = item;
    return height > 256 ? largeSize : smallSize;
};

迭代器 Iterators 和 生成器 Generators

6.1不要使用 iterators(迭代器) 。请使用高阶函数,例如 map() 和 reduce() 等,而不是像 for-in 或 for-of 这样的循环。

const numbers = [1, 2, 3, 4, 5];
 
// bad
let sum = 0;
for (let num of numbers) {
    sum += num;
}
sum === 15;
 
// good
let sum = 0;
numbers.forEach((num) => {
    sum += num;
});
sum === 15;
 
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
 
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach((num) => {
    increasedByOne.push(num + 1);
});
 
// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);

属性 Properties

7.1使用 点语法(.) 来访问对象的属性

const luke = {
    jedi: true,
    age: 28,
};
 
// bad
const isJedi = luke['jedi'];
 
// good
const isJedi = luke.jedi;

7.2当通过变量访问属性时使用中括号 []。

const luke = {
    jedi: true,
    age: 28,
};
 
function getProp(prop) {
    return luke[prop];
}
 
const isJedi = getProp('jedi');

7.3求幂时使用求幂运算符 **

// bad
const binary = Math.pow(2, 10);
 
// good
const binary = 2 ** 10;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容