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

Executing Actions Prior to Redirecting

I am working on implementing a timer process using a custom JQuery plugin that will redirect to the login page after a specific number of minutes. Additionally, when the timer reaches zero, I need to execute a task, which in this case involves making a cal ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

"Caution: Refs cannot be assigned to function components" message encountered when utilizing a custom component in Next.js

I created a component called HeaderIcon with the following code: function HeaderIcon({ inactiveIcon, activeIcon }) { const [isActive, setIsActive] = useState(false); return ( <div onClick={() => setIsActive(!isActive)}> {isActive ? ...

How to select the li element in a nested menu using jQuery

My goal is to extract the text from a specific li element when it is clicked on. The code snippet provided below outlines the structure: <div> <ul> <li>list item 1</li> <li>list item 2</li> <li> ...

"Troubleshooting: Fixing the 'Firebase Cloud Function admin reference is not a function'

I recently attempted to transform the .WriteOn cloud function in my Firebase app into a scheduled cloud function. The goal was to create a function that would run every 4 days to delete messages older than 2 days. While this worked well for the .WriteOn fu ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

After pressing the button to access the sidebar, all I see is a plain white screen

I've been diligently working on a school project, but I'm encountering some issues with the Sidebar button in the top left corner. Whenever I click on the button, it opens up to display a blank white page. Can anyone provide me with some assistan ...

"Enhancing Real-Time Communication in Angular with Websockets and $rootScope's Apply

Currently, I am experimenting with an Angular application that utilizes a websocket to interact with the backend. I've encountered some challenges in getting Angular's data binding to function correctly. In this scenario, I have developed a serv ...

Maximizing the efficiency of a personalized hook that facilitates data sharing in React

I have developed a unique Custom Hook that looks like the following: import { useEffect, useState } from 'react'; import axios from 'axios'; const myCustomHook = () => { const [countries, setCountries] = useState([]); const [i ...

Importing specific files from within the `node_modules` directory can be achieved by

Hello! I am currently using webpack-simple for VueJS and have installed a theme called AdminLTE. I encountered an issue while trying to import the bootstrap files from AdminLTE into my project. When I run `npm run build`, the application searches inside th ...

The Motion of Rotating and Moving Items

Rotating and translating objects can be tricky. While you can successfully perform both actions, the challenge arises when rotating objects as their orientation gets lost -- causing the objects to move in the direction they are facing. if( keyboar ...

What is the best way to set an initial value retrieved from the useEffect hook into the textField input field?

I am working on an edit page where the initial values of first name, last name, and address are fetched from Firebase Firestore using useEffect. useEffect(() => { const unsubscribe = firestore .collection("users") .doc(uid) ...

How can I transfer form data to a PHP variable using an AJAX request?

Encountering some difficulties, any insights? I have included only the necessary parts of the code. Essentially, I have an HTML form where I aim to extract the value from a field before submission, trigger an ajax call, and fill in another field. It seems ...

The JQuery TextNTags plugin eliminates tag formatting once the trigger syntax has been modified

I have incorporated the JQuery TextNTags plugin into my web application. Here is the original code snippet: $.browser = { webkit: true }; $(function () { $('textarea.tagged_text').textntags({ triggers: {'!': { ...

Issues with Vue Sortable functionality may be causing complications

Currently, I am utilizing vue-sortable and draggable. Although I am able to drag an item above and change its position, the JSON data does not refresh. Here is the existing list: <draggable v-model="this.$store.getters.getDocument.getDocumentAttributes ...

Creating a mandatory 'Select' dropdown field in Vue.js

Hello, I am a beginner in VueJS and I am trying to make a select element from a drop-down list required. I attempted to add the required attribute as shown in the code below. Any suggestions on how to achieve this? Thanks. <v-select ...

Exploring the capabilities of Angular 2 and delving into inquiries regarding IIS

I'm diving into the world of Angular 2 as a beginner. Previously, I used to include JavaScript (like jQuery.js) in my HTML and then upload the finished page to my IIS website. Now that I'm learning Angular 2, I've had to install Node.js, NP ...

What is the functionality of the save callback in Mongoose?

Currently in the process of learning about Mongoose's save() function for the MEAN stack. This particular function requires a callback as outlined in its API documentation: Model#save([options], [fn]) Saves this document. Parameters: [options] < ...

Range slider position not being updated after user interaction

I am working on a webpage with an embedded video and a range slider that serves as a progress bar. Using Javascript, I update the value of the range slider as the video plays, allowing users to navigate through the video content. However, I have encounter ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...