幾個簡單的技巧讓你寫出的vue.js程式碼更優雅
本文參考自油管上某個國外大神的公開演講視訊,學習了一下覺得很不錯,所以在專案中也使用了這些不錯的技巧。

1. watch 與 computed 的巧妙結合
如上圖,一個簡單的列表頁面。
你可能會這麼做:
created(){ this.fetchData() }, watch: { keyword(){ this.fetchData() } }
如果引數比較多,比如上圖
- 關鍵字篩選,
- 區域篩選,
- 裝置ID篩選,
- 分頁數,
- 每頁幾條資料,
可能會是這樣:
data(){ return { keyword:'', region:'', deviceId:'', page:1 } }, methods:{ fetchData(paramrs={ keyword:this.keyword, region:this.region, deviceId:this.deviceId, page:this.page, }){ this.$http.get("/list",paramrs).then("do some thing") } }, created(){ this.fetchData() }, watch: { keyword(data){ this.keyword=data this.fetchData() }, region(data){ this.region=data this.fetchData() }, deviceId(data){ this.deviceId=data this.fetchData() }, page(data){ this.page=data this.fetchData() }, requestParams(params){ this.fetchData(params) } }
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提升思維能力
群內有大量PDF可供自取,更有乾貨實戰專案視訊進群免費領取。
不過這麼寫,明顯有問題,主要是 watch
了很多引數,而且函式的處理都差不多,可以修改一下,通過 methods
處理
data(){ return { keyword:'', region:'', deviceId:'', page:1 } }, methods:{ paramsChange(paramsName,paramsValue){ this[paramsName]=paramsValue this.fetchData() }, fetchData(paramrs={ keyword:this.keyword, region:this.region, deviceId:this.deviceId, page:this.page, }){ this.$http.get("/list",paramrs).then("do some thing") } }, created(){ this.fetchData() } //前端全棧學習交流圈:866109386 //面向1-3經驗年前端開發人員 //幫助突破技術瓶頸,提升思維能力
當然這麼寫,需要在模板裡面每個引數change的地方繫結事件,並傳遞引數值,比如分頁change時:
<el-pagination layout="total, prev, pager, next, jumper" :total="total" prev-text="上一頁" next-text="下一頁" @current-change="paramsChange('page',$event)" > </el-pagination>
相比上面的各種watch,程式碼明顯少了很多,但是還有一個問題,那就是要在template的很多地方繫結 change
事件。
最後,當然是使用我們重點推薦的 computed
+ watch
了
data(){ return { keyword:'', region:'', deviceId:'', page:1 } }, computed:{ requestParams() { return { page: this.page, region: this.region, id: this.deviceId, keyword: this.keyword } } }, methods:{ fetchData(paramrs={ keyword:this.keyword, region:this.region, deviceId:this.deviceId, page:this.page, }){ this.$http.get("/list",paramrs).then("do some thing") } }, watch: { requestParams: { handler: 'fetchData', immediate: true } }, //前端全棧學習交流圈:866109386 //面向1-3經驗年前端開發人員 //幫助突破技術瓶頸,提升思維能力
通過增加一個computed屬性,watch這個屬性並設定immediate為true,無需再手動繫結事件,相比之上的方法都要簡潔。當然,缺點就是對效能稍微有些影響,不過問題不大。
2. 使用mixin提取公共部分
很多列表頁其實使用的很多屬性都是一樣的,比如
- 分頁 page
- 數量 size
- 搜尋關鍵 字keyword
- 表格資料 tableData
這些公共的部分其實可以通過mixin來提取出來
/** * mixin/table.js */ export default { data() { return { keyword: '', requestKeyword: '', pages: 1, size: 10, total: 0, tableData: [] } } }
在要用到的頁面
import mixin from '@/mixin/table' export default { mixins: [mixin], data() { return { selectRegion: '', selectDevice: '', deviceList: [], } } /* 其他程式碼 */ ...
3. 自動註冊全域性元件
正常情況下,我們需要使用一個我們自己封裝的元件時,需要先引入,再註冊,最後才能在template模板中使用。
<template> <all-region :selectRegion="selectRegion" @region-change="selectRegion=$event"/> </template> <script> import AllRegion from './baseButton' export default { components: { AllRegion, } } </script>
當有多個頁面需要用到這些元件時,那麼就需要在每個需要的頁面重複這些步驟。
為了簡化這些步驟,可以考慮把這些元件作為全域性元件來使用,這樣每個頁面需要時,就可以直接使用了。
不過還有一個問題,那就是需要我們手動的全域性註冊。
/* main.js */ import Component1 from '@/component/compenent1' import Component2 from '@/component/compenent2' import Component3 from '@/component/compenent3' Vue.component('component1', Component1) Vue.component('component2', Component2) Vue.component('component3', Component3)
當元件多了以後,手動註冊也變得繁瑣起來,可以通過 require.context()
實現自動註冊元件。
/** * main.js * 讀取componetns下的vue檔案並自動註冊全域性元件 */ const requireComponent = require.context('./components', false, /\.vue$/) requireComponent.keys().forEach(fileName => { const componentConfig = requireComponent(fileName) const componentName = fileName.replace(/^\.\//, '').replace(/\.vue/, '') Vue.component(componentName, componentConfig.default || componentConfig) })
4. 自動註冊vuex模組
之前我們是這麼註冊vuex模組的
/* module.js */ import alarm from './modules/alarm' import history from './modules/history' import factory from './modules/factory' import contact from './modules/contact' import company from './modules/company'; import deviceManage from './modules/device-manage' import deviceModel from './modules/device-model' import deviceActivation from './modules/device-activation' import user from './modules/user' import role from './modules/role' import setAlarm from './modules/setAlarm' import factoryMode from "./modules/factoryMode"; import ScreenDeviceWatch from './modules/screen-device-watch' import ScreenDeviceForecast from './modules/screen-device-forecast' export default { alarm, company, deviceManage, deviceModel, user, factory, contact, deviceActivation, history, role, setAlarm, factoryMode, ScreenDeviceWatch, ScreenDeviceForecast, } /* index.js */ import Vue from 'vue' import Vuex from 'vuex' import state from './state' import getters from './getters' import modules from './modules' import actions from './actions' import mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({ state, getters, mutations, actions, modules })
可以發現每個模組都要我們手動匯入,然後加入到module裡面,如此重複。當模組不多還好,假如專案大了,有50個模組,那就得要做很多重複的工作。
跟註冊元件一樣,我們還是利用 require.context
來實現。
/** * 讀取./modules下的所有js檔案並註冊模組 */ const requireModule = require.context('./modules', false, /\.js$/) const modules = {} requireModule.keys().forEach(fileName => { const moduleName = fileName.replace(/(\.\/|\.js)/g, '') modules[moduleName] = { namespaced: true, ...requireModule(fileName).default } }) export default modules /* index.js */ import Vue from 'vue' import Vuex from 'vuex' import modules from './modules' Vue.use(Vuex) export default new Vuex.Store({ state, getters, mutations, actions, modules })
最後

其實,很多想學習技術的同學都一方面是興趣使然一方面是想找一份滿意的工作,如果你學的技術對企業沒有實際價值,那麼也白瞎,(除非你是理論計算機學家),就目前在“網際網路+”趨勢的引導下,Web前端工程師的需求只會越來越大。剛好目前我也為大家整理了一套資料!歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:866109386