日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

前端:Vue前端开发规范,值得收藏!

發布時間:2023/12/10 vue 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 前端:Vue前端开发规范,值得收藏! 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、強制

1. 組件名為多個單詞

組件名應該始終是多個單詞的,根組件 App 除外。

正例:

export default {name: 'TodoItem',// ... } 復制代碼

反例:

export default {name: 'Todo',// ... } 復制代碼

2. 組件數據

組件的 data 必須是一個函數。

當在組件中使用 data 屬性的時候 (除了 new Vue 外的任何地方),它的值必須是返回一個對象的函數。

正例:

// In a .vue file export default {data () {return {foo: 'bar'}} } // 在一個 Vue 的根實例上直接使用對象是可以的, // 因為只存在一個這樣的實例。 new Vue({data: {foo: 'bar'} }) 復制代碼

反例:

export default {data: {foo: 'bar'} } 復制代碼

3. Prop定義

Prop 定義應該盡量詳細。

在你提交的代碼中,prop 的定義應該盡量詳細,至少需要指定其類型。

正例:

props: {status: String } // 更好的做法! props: {status: {type: String,required: true,validator: function (value) {return ['syncing','synced','version-conflict','error'].indexOf(value) !== -1}} } 復制代碼

反例:

// 這樣做只有開發原型系統時可以接受 props: ['status'] 復制代碼

4. 為v-for設置鍵值

總是用 key 配合 v-for。

在組件上_總是_必須用 key 配合 v-for,以便維護內部組件及其子樹的狀態。甚至在元素上維護可預測的行為,比如動畫中的對象固化 (object constancy),也是一種好的做法。

正例:

<ul><liv-for="todo in todos":key="todo.id">{{ todo.text }}</li> </ul> 復制代碼

反例:

<ul><li v-for="todo in todos">{{ todo.text }}</li> </ul> 復制代碼

5.避免 v-if 和 v-for 用在一起

永遠不要把 v-if 和 v-for 同時用在同一個元素上。

一般我們在兩種常見的情況下會傾向于這樣做:

  • 為了過濾一個列表中的項目 (比如 v-for="user in users" v-if="user.isActive")。在這種情形下,請將 users 替換為一個計算屬性 (比如 activeUsers),讓其返回過濾后的列表。

  • 為了避免渲染本應該被隱藏的列表 (比如 v-for="user in users" v-if="shouldShowUsers")。這種情形下,請將 v-if 移動至容器元素上 (比如 ul, ol)。

正例:

<ul v-if="shouldShowUsers"><liv-for="user in users":key="user.id">{{ user.name }}</li> </ul> 復制代碼

反例:

<ul><liv-for="user in users"v-if="shouldShowUsers":key="user.id">{{ user.name }}</li> </ul> 復制代碼

6. 為組件樣式設置作用域

對于應用來說,頂級 App 組件和布局組件中的樣式可以是全局的,但是其它所有組件都應該是有作用域的。

這條規則只和單文件組件有關。你不一定要使用 scoped 特性。設置作用域也可以通過 CSS Modules,那是一個基于 class 的類似 BEM 的策略,當然你也可以使用其它的庫或約定。

不管怎樣,對于組件庫,我們應該更傾向于選用基于 class 的策略而不是 scoped 特性。

這讓覆寫內部樣式更容易:使用了常人可理解的 class 名稱且沒有太高的選擇器優先級,而且不太會導致沖突。

正例:

<template><button class="c-Button c-Button--close">X</button> </template> <!-- 使用 BEM 約定 --> <style> .c-Button {border: none;border-radius: 2px; } .c-Button--close {background-color: red; } </style> 復制代碼

反例:

<template><button class="btn btn-close">X</button> </template> <style> .btn-close {background-color: red; } </style> <template><button class="button button-close">X</button> </template> <!-- 使用 `scoped` 特性 --> <style scoped> .button {border: none;border-radius: 2px; } .button-close {background-color: red; } </style> 復制代碼

二、強烈推薦(增強可讀性)

1. 組件文件

只要有能夠拼接文件的構建系統,就把每個組件單獨分成文件。

當你需要編輯一個組件或查閱一個組件的用法時,可以更快速的找到它。

正例:

components/ |- TodoList.vue |- TodoItem.vue 復制代碼

反例:

Vue.component('TodoList', {// ... }) Vue.component('TodoItem', {// ... }) 復制代碼

2. 單文件組件文件的大小寫

單文件組件的文件名應該要么始終是單詞大寫開頭 (PascalCase)

正例:

components/ |- MyComponent.vue 復制代碼

反例:

components/ |- myComponent.vue |- mycomponent.vue 復制代碼

3. 基礎組件名

應用特定樣式和約定的基礎組件 (也就是展示類的、無邏輯的或無狀態的組件) 應該全部以一個特定的前綴開頭,比如 Base、App 或 V。

正例:

components/ |- BaseButton.vue |- BaseTable.vue |- BaseIcon.vue 復制代碼

反例:

components/ |- MyButton.vue |- VueTable.vue |- Icon.vue 復制代碼

4. 單例組件名

只應該擁有單個活躍實例的組件應該以 The 前綴命名,以示其唯一性。

這不意味著組件只可用于一個單頁面,而是每個頁面只使用一次。這些組件永遠不接受任何 prop,因為它們是為你的應用定制的,而不是它們在你的應用中的上下文。如果你發現有必要添加 prop,那就表明這實際上是一個可復用的組件,只是目前在每個頁面里只使用一次。

正例:

components/ |- TheHeading.vue |- TheSidebar.vue 復制代碼

反例:

components/ |- Heading.vue |- MySidebar.vue 復制代碼

5. 緊密耦合的組件名

和父組件緊密耦合的子組件應該以父組件名作為前綴命名。

如果一個組件只在某個父組件的場景下有意義,這層關系應該體現在其名字上。因為編輯器通常會按字母順序組織文件,所以這樣做可以把相關聯的文件排在一起。

正例:

components/ |- TodoList.vue |- TodoListItem.vue |- TodoListItemButton.vue components/ |- SearchSidebar.vue |- SearchSidebarNavigation.vue 復制代碼

反例:

components/ |- SearchSidebar.vue |- NavigationForSearchSidebar.vue 復制代碼

6. 組件名中的單詞順序

組件名應該以高級別的 (通常是一般化描述的) 單詞開頭,以描述性的修飾詞結尾。

正例:

components/ |- SearchButtonClear.vue |- SearchButtonRun.vue |- SearchInputQuery.vue |- SearchInputExcludeGlob.vue |- SettingsCheckboxTerms.vue |- SettingsCheckboxLaunchOnStartup.vue 復制代碼

反例:

components/ |- ClearSearchButton.vue |- ExcludeFromSearchInput.vue |- LaunchOnStartupCheckbox.vue |- RunSearchButton.vue |- SearchInput.vue |- TermsCheckbox.vue 復制代碼

7. 模板中的組件名大小寫

總是 PascalCase 的

正例:

<!-- 在單文件組件和字符串模板中 --> <MyComponent/> 復制代碼

反例:

<!-- 在單文件組件和字符串模板中 --> <mycomponent/> <!-- 在單文件組件和字符串模板中 --> <myComponent/> 復制代碼

8. 完整單詞的組件名

組件名應該傾向于完整單詞而不是縮寫。

正例:

components/ |- StudentDashboardSettings.vue |- UserProfileOptions.vue 復制代碼

反例:

components/ |- SdSettings.vue |- UProfOpts.vue 復制代碼

9. 多個特性的元素

多個特性的元素應該分多行撰寫,每個特性一行。

正例:

<imgsrc="https://vuejs.org/images/logo.png"alt="Vue Logo" > <MyComponentfoo="a"bar="b"baz="c" /> 復制代碼

反例:

<img src="https://vuejs.org/images/logo.png" alt="Vue Logo"> <MyComponent foo="a" bar="b" baz="c"/> 復制代碼

10. 模板中簡單的表達式

組件模板應該只包含簡單的表達式,復雜的表達式則應該重構為計算屬性或方法。

復雜表達式會讓你的模板變得不那么聲明式。我們應該盡量描述應該出現的是什么,而非如何計算那個值。而且計算屬性和方法使得代碼可以重用。

正例:

<!-- 在模板中 --> {{ normalizedFullName }} // 復雜表達式已經移入一個計算屬性 computed: {normalizedFullName: function () {return this.fullName.split(' ').map(function (word) {return word[0].toUpperCase() + word.slice(1)}).join(' ')} } 復制代碼

反例:

{{fullName.split(' ').map(function (word) {return word[0].toUpperCase() + word.slice(1)}).join(' ') }} 復制代碼

11. 簡單的計算屬性

正例:

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))} } 復制代碼

12. 帶引號的特性值

非空 HTML 特性值應該始終帶引號 (單引號或雙引號,選你 JS 里不用的那個)。

在 HTML 中不帶空格的特性值是可以沒有引號的,但這樣做常常導致帶空格的特征值被回避,導致其可讀性變差。

正例:

<AppSidebar :style="{ width: sidebarWidth + 'px' }"> 復制代碼

反例:

<AppSidebar :style={width:sidebarWidth+'px'}> 復制代碼

13. 指令縮寫

都用指令縮寫 (用 : 表示 v-bind: 和用 @ 表示 v-on:)

正例:

<input@input="onInput"@focus="onFocus" > 復制代碼

反例:

<inputv-bind:value="newTodoText":placeholder="newTodoInstructions" > 復制代碼

三、推薦

1. 單文件組件的頂級元素的順序

單文件組件應該總是讓<script>、<template> 和 <style> 標簽的順序保持一致。且 <style> 要放在最后,因為另外兩個標簽至少要有一個。

正例:

<!-- ComponentA.vue --> <template>...</template> <script>/* ... */</script> <style>/* ... */</style> 復制代碼

四、謹慎使用 (有潛在危險的模式)

1. 沒有在 v-if/v-if-else/v-else 中使用 key

如果一組 v-if + v-else 的元素類型相同,最好使用 key (比如兩個 <div> 元素)。

正例:

<divv-if="error"key="search-status" >錯誤:{{ error }} </div> <divv-elsekey="search-results" >{{ results }} </div> 復制代碼

反例:

<div v-if="error">錯誤:{{ error }} </div> <div v-else>{{ results }} </div> 復制代碼

2. scoped 中的元素選擇器

元素選擇器應該避免在 scoped 中出現。

在 scoped 樣式中,類選擇器比元素選擇器更好,因為大量使用元素選擇器是很慢的。

正例:

<template><button class="btn btn-close">X</button> </template> <style scoped> .btn-close {background-color: red; } </style> 復制代碼

反例:

<template><button>X</button> </template> <style scoped> button {background-color: red; } </style> 復制代碼

3. 隱性的父子組件通信

應該優先通過 prop 和事件進行父子組件之間的通信,而不是 this.$parent 或改變 prop。

正例:

Vue.component('TodoItem', {props: {todo: {type: Object,required: true}},template: `<input:value="todo.text"@input="$emit('input', $event.target.value)">` }) 復制代碼

反例:

Vue.component('TodoItem', {props: {todo: {type: Object,required: true}},methods: {removeTodo () {var vm = thisvm.$parent.todos = vm.$parent.todos.filter(function (todo) {return todo.id !== vm.todo.id})}},template: `<span>{{ todo.text }}<button @click="removeTodo">X</button></span>` }) 復制代碼

4. 非 Flux 的全局狀態管理

應該優先通過 Vuex 管理全局狀態,而不是通過 this.$root 或一個全局事件總線。

正例:

// store/modules/todos.js export default {state: {list: []},mutations: {REMOVE_TODO (state, todoId) {state.list = state.list.filter(todo => todo.id !== todoId)}},actions: {removeTodo ({ commit, state }, todo) {commit('REMOVE_TODO', todo.id)}} } <!-- TodoItem.vue --> <template><span>{{ todo.text }}<button @click="removeTodo(todo)">X</button></span> </template> <script> import { mapActions } from 'vuex' export default {props: {todo: {type: Object,required: true}},methods: mapActions(['removeTodo']) } </script> 復制代碼

反例:

// main.js new Vue({data: {todos: []},created: function () {this.$on('remove-todo', this.removeTodo)},methods: {removeTodo: function (todo) {var todoIdToRemove = todo.idthis.todos = this.todos.filter(function (todo) {return todo.id !== todoIdToRemove})}} }) 復制代碼

附錄

1. 推薦使用vs code進行前端編碼,規定Tab大小為2個空格

  • vs code配置

  • {"editor.tabSize": 2,"workbench.startupEditor": "newUntitledFile","workbench.iconTheme": "vscode-icons",// 以下為stylus配置"stylusSupremacy.insertColons": false, // 是否插入冒號"stylusSupremacy.insertSemicolons": false, // 是否插入分好"stylusSupremacy.insertBraces": false, // 是否插入大括號"stylusSupremacy.insertNewLineAroundImports": false, // import之后是否換行"stylusSupremacy.insertNewLineAroundBlocks": false, // 兩個選擇器中是否換行"vetur.format.defaultFormatter.html": "js-beautify-html","eslint.autoFixOnSave": true,"eslint.validate": ["javascript",{"language": "html","autoFix": true},{"language": "vue","autoFix": true},"javascriptreact","html","vue"],"eslint.options": { "plugins": ["html"] },"prettier.singleQuote": true,"prettier.semi": false,"javascript.format.insertSpaceBeforeFunctionParenthesis": false,"vetur.format.js.InsertSpaceBeforeFunctionParenthesis": false,"vetur.format.defaultFormatter.js": "prettier",// "prettier.eslintIntegration": true } 復制代碼
  • vs code 插件

    • Auto Close Tag

    • Path Intellisense

    • Prettier

    • Vetur

    • vscode-icons

    總結

    以上是生活随笔為你收集整理的前端:Vue前端开发规范,值得收藏!的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。