Bringing in a standard library to a Vue single-page application

Struggling to grasp what should be a straightforward task, I'm open to the idea that my current approach may not be the best way forward. Currently, we are updating our processes and refining some of the functions within a .js file that houses numerous objects and functions utilized in our applications.

To illustrate, consider the following snippet:

**COMMON.JS**
const dynamicYearColumn= {
    resizable: false, suppressMovable: true, sortable: true, width: 100, menuTabs: [], type: 'numericColumn',
}


const defaultPercentageColumn= {

    resizable: false, suppressMovable: true, sortable: true, width: 150, menuTabs: [], type: 'numericColumn',
    valueFormatter: formatPercent,
    cellStyle: { 'text-align': 'right' },
    cellClass: function (params) { var className = numberToColorClass(params.value); return className }
}

function formatPercent(number) {

    if (isNaN(number.value) == true) { return '-' }
    return isFinite(numberWithCommas(parseFloat(number.value, 2).toFixed(this.defaultDecimalRounding))) ? numberWithCommas(parseFloat(number.value, 2).toFixed(this.defaultDecimalRounding)) + '%' : '?';
}

function numberWithCommas(n) {
    var parts = n.toString().split("."); return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

In my main.js file, I have implemented:

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

Vue.use(commonLibrary)

However, I am facing difficulties in implementing this setup.

If I enclose the code within export default in my common.js, the code needs to be modified, resulting in errors with unrecognized functions like formatPercent.

If I use

export {dynamicYearColumn,defaultPercentageColumn}
, it partially works but the functions remain undefined.

Creating a Mixin also yields similar results, with internal functions being unrecognized, along with advice against loading a large library into Mixins due to poor coding practices.

While there are plenty of resources with examples available, I struggle with the terminology to search for relevant solutions.

In essence, all I need is seamless access to an extensive collection of objects and functions from a single JS file, callable from any component within my Vue SPA.

Answer №1

It seems like you're very close to your goal.

Let's say you want to achieve the following:

import common from './scripts/common.js'

In order to do this, we need common.js to have a default export, starting with export default.

Additionally, if we want to access objects and functions as common.dynamicYearColumn, common.formatPercent, etc., we need common to be an object with properties such as dynamicYearColumn, formatPercent, etc. Some of these properties will be functions, but that detail isn't crucial.

Let's briefly explore how we can construct such an object:

const common = {}
common.dynamicYearColumn = { /* define object properties here */ }
common.formatPercent = function (number) { /* implementation details go here */ }

We could also use object literals to immediately define the object properties:

const common = {
  dynamicYearColumn: { /* define object properties here */ },
  formatPercent: function (number) { /* implementation details go here */ }
}

ES6 introduced some shorthand syntax for creating functions within an object, allowing us to simplify the process even further:

const common = {
  dynamicYearColumn: { /* define object properties here */ },
  formatPercent (number) { /* implementation details go here */ }
}

This is the object structure we aim to create within common.js before exporting it. Putting everything together, it looks like this:

export default {
  dynamicYearColumn: {
    // ...  
  },

  defaultPercentageColumn: {
    // ...
  },

  formatPercent (number) {
    // ...
  },

  numberWithCommas (n) {
    // ...
  }
}

By adding them to the Vue.prototype, as shown in your example, these functions will be accessible within your component as follows:

this.$common.formatPercent(25)

In your templates, you would use them like this:

{{ $common.formatPercent(25) }}

Although this setup works well, please note that you cannot use these functions as filters. In case you wish to do so, you must register them as filters within your plugin.

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 JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Add elements from one array into designated positions within another array

Is there a way to extract the days and months from the current week and store it in an array within a specific field of an object? I need to be able to later iterate through this array to display the data. I am unsure on how to achieve this. <div v-for ...

Exploring the Power of Jest and Vue Test Utils for Unit Testing in VueJS

Having recently started Unit Testing with vue, I am currently working on unit testing a navigation vue component. My initial goal was to test a method that simply sets a boolean value to false upon clicking. Utilizing vuetify, I attempted to replicate a bu ...

Obtaining the URL of the Parent Page Using Javascript

I encountered a situation in which, when I open a modal window dialog from Page1.aspx, if a user attempts to directly open that dialog by copying the URL and pasting it into the browser, I want to prevent the modal window from opening. It should only open ...

How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties a ...

Obtaining and Assigning Filter Values in Material Table

Is there a way to programmatically obtain and adjust filter values with material-table? I am looking to enable users to save filter settings as reports and access them whenever necessary. ...

Is it possible to have 1 million links on a single webpage?

Would the performance suffer if I were to fetch 1 million link elements and add them to the DOM? I am looking to create a navigation list at the top of my website, similar to what Apple has on their site where you can scroll left or right using your keybo ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

The response from getStaticProps in Next.js is not valid

While following the Next.js documentation, I attempted to retrieve data from a local server but encountered an error message: FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0 ...

Why is my Angular form submitting twice?

Currently, I am working on a user registration form using AngularJS with ng-submit and ng-model. However, I am facing an issue where the form triggers submission twice when the user submits it. I have checked for common causes such as declaring the contro ...

Leveraging properties in computed properties (vue)

I'm currently working on a simple 2 component vue app using nuxt, composition api, and typescript. Here's my setup: Parent : <template> <input type="text" v-model="txt"> <Child :txt="txt">& ...

The for loop effectively populates the array with elements, but strangely returns an empty array afterwards

After spending all morning troubleshooting, I finally got this code to run successfully and add elements to the array. However, a perplexing issue arises when I try to return the array as it comes back empty. It's been a frustrating morning of debuggi ...

Is it possible to load a JavaScript file from a different domain using a bookmarklet?

I'm a newcomer to bookmarklets and I am experimenting with loading a JavaScript file from my own server/domain using the following bookmarklet/javascript code: javascript:(function(){s=document.createElement('script'); s.type=' ...

JavaScript code that loads a specific DIV element only after the entire webpage has finished loading

How can I ensure that the DIV "image" is loaded only after the entire page has finished loading? What JavaScript code should I use? <div class="row"> <div class="image"> CONTENT </div> </div> I plan to execute the functio ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...