幾個(gè)你不知道的技巧助你寫(xiě)出更優(yōu)雅的vue.js代碼
1. watch 與 computed 的巧妙結(jié)合
如上圖,一個(gè)簡(jiǎn)單的列表頁(yè)面。
你可能會(huì)這么做:
created(){ this.fetchData() }, watch: { keyword(){ this.fetchData() } }
如果參數(shù)比較多,比如上圖
- 關(guān)鍵字篩選,
- 區(qū)域篩選,
- 設(shè)備ID篩選,
- 分頁(yè)數(shù),
- 每頁(yè)幾條數(shù)據(jù),
可能會(huì)是這樣:
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) } }
不過(guò)這么寫(xiě),明顯有問(wèn)題,主要是watch
了很多參數(shù),而且函數(shù)的處理都差不多,可以修改一下,通過(guò)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() }
當(dāng)然這么寫(xiě),需要在模板里面每個(gè)參數(shù)change的地方綁定事件,并傳遞參數(shù)值,比如分頁(yè)change時(shí):
<el-pagination layout="total, prev, pager, next, jumper" :total="total" prev-text="上一頁(yè)" next-text="下一頁(yè)" @current-change="paramsChange('page',$event)" > </el-pagination>
相比上面的各種watch,代碼明顯少了很多,但是還有一個(gè)問(wèn)題,那就是要在template的很多地方綁定change
事件。
最后,當(dāng)然是使用我們重點(diǎn)推薦的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 } },
通過(guò)增加一個(gè)computed屬性,watch這個(gè)屬性并設(shè)置immediate為true,無(wú)需再手動(dòng)綁定事件,相比之上的方法都要簡(jiǎn)潔。當(dāng)然,缺點(diǎn)就是對(duì)性能稍微有些影響,不過(guò)問(wèn)題不大。
2. 使用mixin提取公共部分
很多列表頁(yè)其實(shí)使用的很多屬性都是一樣的,比如
- 分頁(yè) page
- 數(shù)量 size
- 搜索關(guān)鍵 字keyword
- 表格數(shù)據(jù) tableData
這些公共的部分其實(shí)可以通過(guò)mixin來(lái)提取出來(lái)
/** * mixin/table.js */ export default { data() { return { keyword: '', requestKeyword: '', pages: 1, size: 10, total: 0, tableData: [] } } }
在要用到的頁(yè)面
import mixin from '@/mixin/table' export default { mixins: [mixin], data() { return { selectRegion: '', selectDevice: '', deviceList: [], } } /* 其他代碼 */ ...
3. 自動(dòng)注冊(cè)全局組件
正常情況下,我們需要使用一個(gè)我們自己封裝的組件時(shí),需要先引入,再注冊(cè),最后才能在template模板中使用。
<template> <all-region :selectRegion="selectRegion" @region-change="selectRegion=$event"/> </template> <script> import AllRegion from './baseButton' export default { components: { AllRegion, } } </script>
當(dāng)有多個(gè)頁(yè)面需要用到這些組件時(shí),那么就需要在每個(gè)需要的頁(yè)面重復(fù)這些步驟。
為了簡(jiǎn)化這些步驟,可以考慮把這些組件作為全局組件來(lái)使用,這樣每個(gè)頁(yè)面需要時(shí),就可以直接使用了。
不過(guò)還有一個(gè)問(wèn)題,那就是需要我們手動(dòng)的全局注冊(cè)。
/* 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)
當(dāng)組件多了以后,手動(dòng)注冊(cè)也變得繁瑣起來(lái),可以通過(guò)require.context()
實(shí)現(xiàn)自動(dòng)注冊(cè)組件。
/** * main.js * 讀取componetns下的vue文件并自動(dòng)注冊(cè)全局組件 */ 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. 自動(dòng)注冊(cè)vuex模塊
之前我們是這么注冊(cè)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 })
可以發(fā)現(xiàn)每個(gè)模塊都要我們手動(dòng)導(dǎo)入,然后加入到module里面,如此重復(fù)。當(dāng)模塊不多還好,假如項(xiàng)目大了,有50個(gè)模塊,那就得要做很多重復(fù)的工作。
跟注冊(cè)組件一樣,我們還是利用require.context
來(lái)實(shí)現(xiàn)。
/** * 讀取./modules下的所有js文件并注冊(cè)模塊 */ 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 })
這篇關(guān)于如何寫(xiě)出更優(yōu)雅的vue.js代碼的文章就介紹到這了,希望大家以后多多支持腳本之家。
相關(guān)文章
Vue 設(shè)置axios請(qǐng)求格式為form-data的操作步驟
今天小編就為大家分享一篇Vue 設(shè)置axios請(qǐng)求格式為form-data的操作步驟,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10Vue3中動(dòng)態(tài)修改樣式與級(jí)聯(lián)樣式優(yōu)先順序圖文詳解
在項(xiàng)目中,我們時(shí)常會(huì)遇到動(dòng)態(tài)的去綁定操作切換不同的CSS樣式,下面這篇文章主要給大家介紹了關(guān)于Vue3中動(dòng)態(tài)修改樣式與級(jí)聯(lián)樣式優(yōu)先順序的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04vue單行文本溢出會(huì)出現(xiàn)title提示自定義指令
這篇文章主要為大家介紹了vue單行文本溢出會(huì)出現(xiàn)title提示自定義指令,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01vue如何實(shí)現(xiàn)多組關(guān)鍵詞對(duì)應(yīng)高亮顯示
這篇文章主要介紹了vue如何實(shí)現(xiàn)多組關(guān)鍵詞對(duì)應(yīng)高亮顯示問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10vue2.0/3.0中provide和inject的用法示例
provide和inject是成對(duì)出現(xiàn)的,主要用于父組件向子孫組件傳遞數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于vue2.0/3.0中provide和inject用法的相關(guān)資料,需要的朋友可以參考下2021-09-09發(fā)布訂閱模式在vue中的實(shí)際運(yùn)用實(shí)例詳解
訂閱發(fā)布模式定義了一種一對(duì)多的依賴(lài)關(guān)系,讓多個(gè)訂閱者對(duì)象同時(shí)監(jiān)聽(tīng)某一個(gè)主題對(duì)象。這篇文章主要介紹了發(fā)布訂閱模式在vue中的實(shí)際運(yùn)用,需要的朋友可以參考下2019-06-06