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