几个你所不知道的技巧助你写出更优雅的vue.js代码

1. watch 与 computed 的巧妙结合

如上图,一个简单的列表页面。javascript

你可能会这么作:vue

created(){
        this.fetchData()
    },
    
    watch: {
        keyword(){
            this.fetchData()
        }
    }

若是参数比较多,好比上图java

  • 关键字筛选,
  • 区域筛选,
  • 设备ID筛选,
  • 分页数,
  • 每页几条数据,

可能会是这样:vuex

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 + watchfetch

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,无需再手动绑定事件,相比之上的方法都要简洁。固然,缺点就是对性能稍微有些影响,不过问题不大。ui

2. 使用mixin提取公共部分

不少列表页其实使用的不少属性都是同样的,好比this

  • 分页 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
})

本文参考自油管上某个国外大神的公开演讲视频,学习了一下以为很不错,因此在项目中也使用了这些不错的技巧。趁周末有空,写个博客记录一下。

相关文章
相关标签/搜索