幾個你所不知道的技巧助你寫出更優雅的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)
    }
}

不過這么寫,明顯有問題,主要是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()
}

當然這么寫,需要在模板里面每個參數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
    }
},

通過增加一個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模塊的 ```javascript /* 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`來實現。
```javascript
/**
 * 讀取./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
})

本文參考自油管上某個國外大神的公開演講視頻,學習了一下覺得很不錯,所以在項目中也使用了這些不錯的技巧。趁周末有空,寫個博客記錄一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM