標籤:domain ons UNC @hide hide select some .post log
一、簡介
團隊合作中規範文檔是必須的,在多人合作的項目只有定義好一定的編碼規範才會使得開發井井有序,代碼一目瞭然,下邊將談一下個人對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.後續繼續完善。。。
vue開發規範