Vue 基本文件编码规范

记录一些 Vue 开发的一些基础编码规范

更详细的编码风格规范可参考官方风格指南

😮更详细的官方风格指南 - Vue.js😏

1. 文件规范

1.1 文件命名

两种风格,除了文件夹下的默认文件 index.vue,其他以以下两种风格为准

a. 单词大写开头 (PascalCase)

UserInfo.vue

b. 横线连接 (kebab-case)

user-info.vue

反例

userInfo.vue
userinfo.vue

单词大写开头对于代码编辑器的自动补全最为友好,因为这使得我们在 JS(X) 和模板中引用组件的方式尽可能的一致。然而,混用文件命名方式有的时候会导致大小写不敏感的文件系统的问题,这也是横线连接命名同样完全可取的原因。

1.2 文件夹结构

确定有父子组件关系的文件建议将子组件统一放到具体文件夹,例如文章详情页面中有文章内容组件

ArticleDetail → ArticleContent

article /
	copoments/
		- ArticleContent.vue
		- ArticleComment.vue
-	index.vue (默认路由文章详情页面 ArticleDetail )

反例

article/
	-ArticleContent.vue
	-ArticleComment.vue
	-index.vue (默认路由文章详情页面 ArticleDetail )

1.3 特定类型组件命名

a. 基础组件

建议以固定前缀命名,例如 Base、App 或 V

components/
	- BaseButton.vue
	- BaseTable.vue
	- BaseRadio.vue

b. 单例组件

指在页面中只会使用一次的组件,建议以 The 作为前缀标识唯一性

components/
	- TheArticleHeader.vue
	- TheArticleContent.vue
	- TheArticleFooter.vue

c. 耦合组件

指在业务或功能上紧密相关的组件,建议以统一功能或业务名称作为前缀,例如待做事件 Todo

components/
	- TodoList.vue
	- TodoItem.vue
	- TodoContent.vue

1.4 文件拼写

建议全拼命名而不是简略缩写命名

UserInfoSetting.vue

反例

UserIS.vue

2. 编码规范

2.1 Prop 参数编码

a. 命名

在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板和 JSX 中应该始终使用 kebab-case

子组件
props: {
	userInfo: Object
}

--------------------------------------
父组件
<user user-info='data' />

反例

子组件
props: {
	userInfo: Object
}

-------------------------------------
父组件
<user userInfo='data' />

b. 参数定义

在子组件的 prop 参数定义中,应指定参数类型和默认值

props: {
	id: {
		type: Number,
		default: null
	}
}

反例

props: {
	id: Number
}

若参数类型为 Object / Array 类型,应以函数形式指定默认值

props: {
	userInfo: {
		type: Object,
		default: function() {
        return {...}
    }
	}
}

反例

props: {
	userInfo: {
		type: Object,
		default: {...}
	}
}

2.2 组件 attribute

当组件有多个 attribute (属性或参数) 时,每个 attribute 应占一行,方便阅读

<user 
	id='' 
	name='' 
	password='' 
/>

反例

<user id='' name='' password='' />

2.3 Computed 计算属性

计算属性中应避免复杂的运算,尽可能拆分独立计算

computed: {
  basePrice: function () {
    return this.manufactureCost / (1 - this.profitMargin)
  },
  discount: function () {
    return this.basePrice * (this.discountPercent || 0)
  },
  finalPrice: function () {
    return this.basePrice - this.discount
  }
}

反例

computed: {
  price: function () {
    var basePrice = this.manufactureCost / (1 - this.profitMargin)
    return (
      basePrice -
      basePrice * (this.discountPercent || 0)
    )
  }
}

仅供参考,谢谢围观 😄

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值