Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex

To make logging methods accessible to all components, I am utilizing a global 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);
        }
    }
}

And here is the enumeration utilized :

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

I am exploring options for dynamically declaring these functions. For instance, creating a method automatically for each $l Level in LogLevel:

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

Any suggestions would be appreciated.

Answer №1

A solution is available here: 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')
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Checking for the accuracy of the provided full name

There is a specific task at hand: The field labeled “First Name Last Name” must only contain 2 words, with each word being between 3 and 30 characters in length. Additionally, there should be only one space between the first and last name. The issue t ...

Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

The process of utilizing the override feature in the package.json file to make updates to child dependencies

There seems to be a vulnerability in the async package that I want to update to version 3.2.2. Here is the dependency tree if I use npm list async: └─┬ [email protected] └─┬ [email protected] └── [email protected] After referring t ...

In React Native, the onPress handler will continue to be triggered indefinitely after 2-3 presses

import firebase from './Firebase'; import { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, FlatList } from 'react-native'; import { TextInput } from 'react-native-web'; import { setStatu ...

Sending data from a parent component to a child component through a function

In the process of developing an app, I have implemented a feature where users must select options from four dropdown menus. Upon clicking the "OK" button, I aim to send all the selections to a child component for chart creation. Initially, I passed the sel ...

Tips for showing data associated with the chosen option from a dropdown list in Angular.js fetched from an API

My goal is to automatically display the coordinator's name based on the selection in a dropdown list populated with data from an API. The dropdown options are the email addresses from the JSON data below, and upon selecting a login ID, the correspondi ...

Navigating array usage in Selenium IDE

I am trying to extract emails from a webpage using Selenium for future testing. I need to compare these emails with ones displayed in a selection later on. I attempted to read the emails within a while-loop but struggled with handling arrays in IDE. Unfor ...

There is an issue with adding data to the database after inputting email and password for authorization in Firebase via Vue.js

The data is not being added to the database even after entering the email and password for authorization in Firebase using vue.js. When I use: firebase.auth().createUserWithEmailAndPassword(this.email, this.password) The following code does not get execu ...

Is it possible to utilize a JavaScript variable in this particular scenario and if so, what is the

let myVariable = <?php echo json_encode($a[i want to insert the JS variable here]); ?>; Your prompt response would be highly valued. Many thanks in advance. ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Accessing the admin panel of a headless CMS using Nuxt.js and WordPress

I'm facing an issue. I recently set up Wordpress and enabled the REST API. Following that, I created a Nuxt.js app. The app runs on localhost:3000 (using "npm run dev" command) I configured XAMPP so that the document root of the server points to the ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

How do I retrieve the host name of a webpage in server-side rendering using Nuxt.js?

Within my Nuxt.js project, I have a configuration variable for the API environment structured as follows: [ { front_host: local-1.domain.com, backend_api: api-1.domain.com }, { front_host: local-2.domain.com, backend_api: api-2.domain.com }, ] I ...

Dropzone JavaScript returns an 'undefined' error when attempting to add an 'error event'

When using Dropzone, there is a limit of 2 files that can be uploaded at once (maxFiles: 2). If the user attempts to drag and drop a third file into the Dropzone area, an error will be triggered. myDropzone.on("maxfilesexceeded", function(file){ a ...

Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {}); I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign ...

Creating a carousel of cards using JavaScript, CSS, and HTML

Here is a visual reference of what I'm attempting to achieve: https://i.stack.imgur.com/EoQYV.png I've been working on creating a carousel with cards, but I'm struggling to synchronize the button indicators with card advancement when clicke ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...