Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application.

One of the functions in this library that I find particularly useful is:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

Whenever "formatNumber" is called, it rounds the number to a specific decimal point, defined by the variable "defaultDecimalRounding"

However, I would like to be able to change this defaultDecimalRounding value within my Vue App instead of having it hardcoded in commonLibrary.js.

To achieve this, I tried creating a Mixin:

Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});

Unfortunately, I encountered an issue where my formatNumber function couldn't access this defaultDecimalRounding Mixin.

Although I am open to rewriting the code in commonLibrary.js, which only contains a few functions, I am curious about how to establish communication between VueJS and an imported JS library for future projects.

edit The commonLibrary.js is imported using the following code:

import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)

Answer №1

Follow these steps:

In the common.js file

var defaultDecimalRounding = 3;

// Rename export to prevent naming conflicts
export const defaultDecimal = defaultDecimalRounding;

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

In your Vue application:

import { defaultDecimal } from "./common";

Vue.mixin({
  data: function() {
    return {
      defaultDecimal : defaultDecimal
    };
  }
});

Answer №2

It is probable that the usage of this is necessary due to the fact that defaultDecimalRounding has been defined within the Vue instance. You may need to access it using this.defaultDecimalRounding

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

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

In Vue, applying CSS styles to D3's SVG elements may not work as expected when using the scoped attribute

Here is the code snippet of my component: <template> <div id="something" class="card"> </div> </template> const height = 200; const width = 200; let graph = d3 .select('#something') .append('svg') ...

Loop through JSON data using jQuery for parsing

Here is the code snippet I have included below, which is a part of a larger code base: <html> <head> <style> #results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;} </style> & ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

What is the best way to change a canvas into an image while preserving transparency?

Currently, I am attempting to modify a weather radar image with a black background by making the background transparent using canvas. However, when I view the modified image, instead of transparency, the background now appears as a red and black checkerboa ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

Accessing clipboard contents upon button click using TypeScript

Seeking assistance with retrieving data from the clipboard in TypeScript after clicking on a button. Please provide guidance. Thank you! ...

Detecting drag events between connected angular ui-trees is a complex yet achievable task

How can I trigger an action when an item is dragged from tree#1 to tree#2 and dropped? I want to make a specific HTTP call to save the transferred item. I have successfully implemented actions within one tree using the 'dropped' event, but strugg ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Is there a way to determine if a Dojo dialog has been successfully loaded on the page?

I have a function that needs to close a Dojo dialog if it is currently open. How can I determine if a dojo dialog is active? Should I rely on pure JavaScript and check for its existence by ID? if (dijit.byId("blah") !== undefined) { destroyRecursive ...

Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve: create() { const map = this.make. ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

ajaxStart event does not trigger when making an Ajax POST request

My ajaxStart event functions properly for ajax loads, but it does not work at all when I do a POST request. The following code is consistently rendered on all pages: $(document).ajaxComplete(function () { hideIcon(); if (stepState !== &a ...