H
H
HiDiv2021-07-12 18:13:34
Vue.js
HiDiv, 2021-07-12 18:13:34

How to dynamically register locally a new vue component?

I have a page component that receives data to display from an external source via ajax. The project itself implements quite a lot of widgets for different types of fields (components that can be used on the form). I really don't want to describe them all in componets, even through asynchronous loading, because in fact, no more than 10% -20% of the total number of component widgets is used in one "session" with the data source. The next time data is received, some or even completely different component widgets may be required.

I didn’t find how to dynamically register components at all, but I kind of figured out how to do it globally:

export function registerFieldComponents(prefix: string, fieldTypes: string[]) {
  fieldTypes.forEach(type => {
    const compName = getComponentNameForField(prefix, type)
    const comp = Vue.component(compName)
    if (typeof comp === 'undefined') {
      Vue.component(compName, () => import('components/fields/' + type + '/' + compName + '.vue'))
    }
  })
}

Such a solution, for some reason, periodically stops working, i.e. the process of registering new components is performed and Vue.component for new types is called, but on the page component itself in this.$options.components (in the proto section of course) there are no globally registered components ... And not all, but only a part that are added when next data update.

Again. The main task is to dynamically (if necessary) register additional components (preferably locally), the paths and names of which are known (by mask), but at the same time not to explicitly prescribe each of these components.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-07-12
@Kozack Vue.js

Vue components are ordinary objects with certain properties. And you can create them anytime, anywhere.
Here is an example

A
Aetae, 2021-07-13
@Aetae

In general, your solution should work. If it doesn't work, and not right away, you need to debug it and possibly report it.
As a workaround, you can try registering all of them at once (as dynamic components). The first parameter Vue.component- the name can be require.contextobtained through, the second parameter - a function with import.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question