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

Notify when a certain element's ID is visible on the screen using the jQuery appear method

Having trouble getting this plugin to cooperate: https://github.com/morr/jquery.appear I attempted to reference the plugin from a CDN using Ajax: http://cdnjs.cloudflare.com/ajax/libs/jquery.appear/0.3.3/jquery.appear.js Why isn't it working as expe ...

Using JQuery to dynamically change className based on specific logic conditions

I am struggling to dynamically change the class name of a div based on the text inside another div using jQuery. Here is an example of the HTML structure: <div class="div-overlay"> <a class="image" href="https://www.e ...

Using jQuery to handle multiple buttons with the same ID

Is there a way to address the issue of multiple buttons sharing the same id? Currently, when clicking on any button, it only updates the record with id=1. How can this problem be resolved? div id="ShowPrace"> <?php try { $stmt = $pdo->prepare(" ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

How to dynamically add table rows and cells with JavaScript using a single selection input

I am working on a project that involves a selection input with around 5 options. Additionally, there is an empty table that follows this format: <table> <tr> <td>X (for deletion)</td> <td>Option name</td> ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...

Looking to disable the back button in the browser using next.js?

How can I prevent the browser's back button from working in next.js? // not blocked... Router.onRouteChangeStart = (url) => { return false; }; Does anyone know of a way to disable the browser's back button in next.js? ...

How can I replicate the functionality of the span element using Javascript?

Using Javascript, I am able to display a paragraph without the need for HTML. By adding it to an HTML id, I can manipulate individual words within the text. My goal is to make specific words cursive while keeping the entire paragraph in its original font s ...

"Exploring ways to pass live data from the controller to the view in CodeIgniter for dynamic chart values

I currently have the following code where I am statically assigning values. Now, I need to dynamically retrieve values and display a chart. I want to populate the 'items' variable from the controller in the same format, and then display the chart ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

Customizing CSS based on URL or parent-child relationship in WordPress

I'm having trouble finding a solution for what seems like a simple issue... Currently, my header has a border-bottom and I'd like to change the color of this border based on the section the user is in. For example, consider these parent pages: ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

vue popup input will automatically receive focus

Currently, I am utilizing Vue 2.x Within a HTML file that is included in a JSP file, the structure looks like this: <html> <body> <div id="myDiv"> <input type="text" v-model="input" @click=&qu ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...