Automatically load VueJS components based on the prefix of the tag

I am currently working on defining components based on the prefix when Vue parses the content (without using Vuex).

While exploring, I came across Vue.config's isUnknownElement function but couldn't find any documentation about it. By utilizing this function, I can call Vue.component (with an async function) if the prefix matches, avoiding the unknown component error. However, the component doesn't render immediately because the async function is not triggered until the next time the tag is parsed.

Up to now, the only workaround I've discovered is to render the component twice (using a v-if and updating the bound variable).

Is there a more efficient way of achieving this?

Why am I doing this? In my single-page applications, I have a series of custom components all sharing a common prefix and path structure, resulting in the component name matching its path (replacing dashes with slashes). This is why having a universal function to dynamically register each component starting with this prefix would be extremely useful :)

Answer №1

My reason for being here aligns with the OP's, and I'm eager to share the solution I stumbled upon.

The key lies in utilizing the isUnknownElement function, as well as drawing insights from these resources:

(1) https://v2.vuejs.org/v2/guide/components-dynamic-async.html#Async-Components

(2) https://forum.vuejs.org/t/why-use-the-no-function-in-vue-source-code-utils/27675

Vue.config.isUnknownElement = function () {
    let tagName = arguments[0].toLowerCase();
    if (/^vc-/i.test(tagName)) {
      // Tags like 'vc-*' pertain to VueJS components

      // It's crucial to ascertain if the component is already defined:
      // https://stackoverflow.com/questions/37389788/vue-js-check-if-a-component-exists
      if (typeof Vue.options.components[tagName] === 'undefined') {
        // Arrange a lazy-loader for the component
        // Remove 'vc-' prefix from tagName to derive the component's name
        let componentName = tagName.substr(3);
        Vue.component(tagName, function (resolve) {
          // ... Load the component 'componentName' in a "lazy" manner, as per link (1)
        });
      }
    }
    return false;  // Mimicking the default Vue configuration's behavior, see link (2)
  };

I've designated custom components using tags prefixed with 'vc-' (for instance, 'vc-table'). Consequently, when a tag with the specified prefix is encountered by the Vue template compiler, a corresponding component is dynamically defined and loaded in a lazy-loading fashion.

Answer №2

After some experimentation, I managed to get my components to autoload based on the rules I set. My approach was similar to @dosorio's, but I chose to use a different function called isReservedTag.

const isReservedTag = Vue.config.isReservedTag;
Vue.config.isReservedTag = (tag, context) => {
  if ( isReservedTag(tag) ){
    return true;
  }
  // Checking if the tag matches any of my rules
  // If it does, then define my component
  if ( checkMyRule(tag) ){
    Vue.component(tag, (resolve) => {
      // Loading the component
    });
  }
  return false;
};

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

What is the process of importing a JSON data file and utilizing it within a React component?

As a beginner in React, I am struggling with the concepts of importing, exporting, and rendering components. I have a fakeData.json file within the same src/components folder as the component I want to render. Let's take a look at the structure: < ...

Python sends back a list containing garbled characters to Ajax

Need help fixing the output of a Python list returned to Ajax, as it appears strange. ap.py @app.route('/_get_comUpdate/', methods=['POST']) def _get_comUpdate(): comNr = request.form.get('comNr') com_result ...

What is the procedure for including a js file in typescript?

I am trying to import a js file in typescript and access objects and functions within the file. I have added the js file in index.html, but it is not working as expected. I tried using "import '[js file path]'" but it did not work. import { Comp ...

Recalling the use of jquery toggle throughout the website?

I have successfully implemented a button to hide and unhide a lengthy menu with a click, but I am struggling to make the menu state persistent across multiple pages. I would like the last toggle action by the visitor to be remembered. Any suggestions on ho ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

"Stuck in a Standstill: Express/React Commit

Currently, I have set up an Express backend server on port 5000 along with a React frontend running on port 3000. My goal is to fetch some data from an Express post route and return it to the frontend, however, I am encountering an issue where my Promise n ...

jquery allows you to toggle the visibility of content

There are two divs with a button positioned above them. Initially, only one div, the catalogusOrderBox, is visible. When the button named manualButton is clicked, it should display the manualOrderBox div while hiding the catalogusOrderBox div. The text on ...

json array: Tips for adding elements to a new array

In order to achieve my goal, I am looking to create a JSON array structure similar to the one shown below: var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; How can I modify the code snippet provided below to generat ...

Error will be thrown if the initialDueDate parameter is deemed invalid in Javascript

Can someone help me improve the calculateNextDueDate function which takes an initialDueDate and an interval to return the next due date? I want to add argument validation to this function. Any suggestions would be greatly appreciated. Thank you! const I ...

Is it possible to utilize Javascript instead of PHP Curl to present JSON API data?

After successfully displaying JSON API data from openweathermap.org on my HTML webpage using PHP Curl, I am now seeking help to achieve the same output using Javascript. My PHP script retrieves JSON data from the source, and here is a snippet of that PHP c ...

Issue with the string formatting in Vue.js is causing unexpected behavior

Hi there, I'm currently working on dynamically styling a div in VueJs and running into an issue with the this.currentProgressLevel not being applied to the width property within the currentStyle object. I've attached a screenshot of the code I&ap ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

Rebooting: Relaunching NodeJS server following deployment

I recently launched my inaugural Laravel Forge website featuring a server-side rendered VueJS 2.0 application. Although I've implemented quick deployment and a daemon to ensure constant operation, I've encountered an issue during deployments. Th ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

Adjust the Vue.js required property to allow null values but not undefined

I need my component to accept both objects and null values, as Vue.js considers null as an object. However, I want the validation to fail if the value is undefined. Here's what I've attempted using vue-property-decorator: @Prop({ required: true ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Adjusting the size of images in real time

Currently, I am in the process of creating a Fluid grid style website and I am looking to decrease the size of all images by 75% when the screen is below 1280px, 50% at 800px, and so forth. Is there a way to achieve this using the IMG tag? My attempt so ...