vue開發規範
一、簡介
團隊合作中規範文件是必須的,在多人合作的專案只有定義好一定的編碼規範才會使得開發井井有序,程式碼一目瞭然,下邊將談一下個人對vue使用規範的一些看法。
二、規範案例
1.元件命名
元件檔名應該始終以單詞大寫開頭(PascalCase),元件名也是以單詞大寫開頭,當多個單詞拼寫成的元件時,單詞開頭大寫,採用駝峰式命名規則。一般是多個單詞全拼,減少簡寫的情況,這樣增加可讀性。元件應該都放到components資料夾下,單個頁面獨立一個資料夾,用來放相對應的vue檔案以及頁面相關的樣式檔案,樣式少可直接寫到頁面元件裡邊,這樣更符合元件化的思想。資料夾名稱應統一格式,小寫開頭,統一以page結尾,比如homePage,loginPage,listPage這樣子的命名。公用元件應該統一放到public檔案下,下邊是例子:
公共的樣式檔案應該抽取放到統一的檔案去統一管理。
2.基礎元件命名
2.1當專案中需要自定義比較多的基礎元件的時候,比如一些button,input,icon,建議以一個統一的單詞Base開頭,或者放到base資料夾統一管理,這樣做的目的是為了方便查詢。例如:
2.2頁面級元件應該放到相對應頁面資料夾下,比如一些元件只有這個頁面用到,其他地方沒有用到的,可以直接放到頁面資料夾,然後以父元件開發命名,例如:
2.3專案級元件一般放到公共資料夾public下給所有的頁面使用。
3.元件結構
元件結構一個遵循從上往下是template,script,style的結構
<template> <div></div> </template> <script> </script> <style> </style>
4.元件樣式
單個元件樣式一般可直接寫到元件下style標籤下,為了防止樣式汙染,可新增scoped 屬性,也可以通過設定作用域來防止樣式汙染,寫樣式的時候儘量少寫元素選擇器,為了提高程式碼查詢速度,可以用類選擇器。
<template> <div class="homePage"> <div class="list"></div> <div class="banner"></div> </div> </template> <script> </script> <style lang="scss" scoped> .homePage{ .list{ } .banner{ } } </style>
5.多屬性編寫格式
當元件定義很多的props值時,應該每個特性屬性一行。
<SelectExportItem v-bind="$attrs" :selectItemList="selectItemList" @hideSelectItem="$emit('hideSelectItem')" @exportReport="exportReport" ></SelectExportItem>
6.props定義
當定義元件時,應該對傳入元件的props進行嚴格的定義,至少指定型別,設定預設值,定義好規範方便他人使用。
props:{ modelflag:{ type:Number, default:0 } }
7.位v-for 增加鍵值Key,這樣加快查詢速度。
<ul> <li v-for="todo in todos" :key="todo.id" > {{ todo.text }} </li> </ul>
8.當頁面用到一些共享的狀態的時,建議使用vuex
9.vue推薦使用axios進行介面請求,然後對專案中做統一的介面攔截處理,封裝適合專案使用的get,post 方法。
import Vue from 'vue' import axios from 'axios' import { encode, decode,toEncode,toDecode} from './base64.js' import Qs from 'qs'; import router from './router' let timeout = 30000; var instance = axios.create({ //baseURL: 'https://some-domain.com/api/', timeout: timeout, responseType: 'json', // default, //headers: {'apikey': 'foobar'}, transformRequest: function(data, headers) { //為了避免qs格式化時對內層物件的格式化先把內層的物件轉為 //由於使用的form-data傳資料所以要格式化 if(!(data instanceof FormData)) { if (typeof data === "string") { headers.post['Content-Type'] = "application/json"; } else { headers.post['Content-Type'] = "application/x-www-form-urlencoded"; for(let key in data) { if(data[key] === undefined) { data[key] = null; } } data = Qs.stringify(data); } } return data; } }); instance.interceptors.request.use(function(config) { // Do something before request is sent //header 新增Request-Token //配置請求頭tocken //配置get請求 return config; }, function(error) { // Do something with request error return Promise.reject(error); }) // Add a response interceptor instance.interceptors.response.use(function(response) { // Do something with response data if (response.data.status===400001) { //access tocken過期30天 vm.$router.push({path:'/login'}) } return response; }, function(error) { // Do something with response error return Promise.reject(error); }); export default instance;
10.後續繼續完善。。。