动态生成的方法VueJS

时间:2019-01-21 14:14:22

标签: javascript vue.js vuejs2

我正在使用VueJS和Vuex为我的javascript项目构思一个日志记录系统

要提供对所有组件的日志记录方法的访问,我使用全局Mixin:

import { mapState, mapActions } from 'vuex'
import LogLevel from '@/enums/logger/LogLevel'

export default {
    computed: {
        ...mapState('Logger', {
            global_logs: 'activities'
        })
    },
    methods: {
        ...mapActions('Logger', {
            clear_logs: 'clear_activities'
        }),

        log_handler(message, data = {}, options = {}) {
            this.$store.dispatch('Logger/add_activity', {
                message: message,
                payload: data,
                ...options,
            });
        },

        log(message, data = {}, options = {}) {
            options.level = options.level ? options.level : LogLevel.INFO;
            this.log_handler(message, data, options);
        },

        log_debug(message, data = {}, options = {}) {
            options.level = LogLevel.DEBUG;
            this.log_handler(message, data, options);
        },

        log_info(message, data = {}, options = {}) {
            options.level = LogLevel.INFO;
            this.log_handler(message, data, options);
        },

        log_error(message, data = {}, options = {}) {
            options.level = LogLevel.ERROR;
            this.log_handler(message, data, options);
        },

        log_warning(message, data = {}, options = {}) {
            options.level = LogLevel.WARNING;
            this.log_handler(message, data, options);
        },

        log_success(message, data = {}, options = {}) {
            options.level = LogLevel.SUCCESS;
            this.log_handler(message, data, options);
        }
    }
}

和使用的枚举:

export const LogLevel = Object.freeze({
    DEBUG: "secondary",
    INFO: "info",
    WARNING: "warning",
    ERROR: "danger",
    SUCCESS: "success"
});

所以,我想知道是否有一种方法可以动态地声明这些函数。例如,对于LogLevel的所有$ l级,我想自动创建方法:

log_$l(message, data = {}, options = {}) {
    options.level = LogLevel.$l;
    this.log_handler(message, data, options);
}

谢谢

1 个答案:

答案 0 :(得分:3)

是的,您可以:https://jsfiddle.net/rhw7uj9L/

const LogLevel = Object.freeze({
    DEBUG: "secondary",
    INFO: "info",
    WARNING: "warning",
    ERROR: "danger",
    SUCCESS: "success"
})

const fns = Object.keys(LogLevel).map(level => {
    return {
        ['log_' + level.toLowerCase()] (message, data = {}, options = {}) {
            options.level = LogLevel[level]
            this.log_handler(message, data, options)
        }
    }
})

const methods = Object.assign(...fns)

new Vue({
  el: "#app",
  data: {},
  methods: {
    log_handler (message, data, options) {
        console.log('logging', message, data, options)
    },
    ...methods
  },
  created () {
    this.log_handler('olas')
    this.log_warning('yess')
    this.log_error('noppp')
  }
})