[Vuejs]-Resolve Vue component names on the fly

0👍

You could create a wrapper <component> that maps the component names and globally registers the specified component on the fly.

  1. Create a component with a prop (e.g., named "xIs") for the <component>‘s is property:

    export default {
    props: {
    xIs: {
    type: String,
    required: true
    }
    },
    };

  2. Add a template that wraps <component>, and a data property (e.g., named "translatedName") that contains the mapped component name (from backend to front-end name):

    export default {
    data() {
    return {
    translatedName: ”
    }
    }
    };

  3. Add a watcher on the prop that will register a component by the name indicated in the prop value:

    import componentNames from ‘./component-names.json’;

    export default {
    watch: {
    xIs: {
    immediate: true, // run handler immediately on current `xIs`
    async handler(value) {
    try {
    const name = componentNames[value]; // 1. lookup real component name
    if (name) {
    Vue.component(name, () => import(`@/components/${name}`)); // 2. register component
    this.translatedName = name; // 3. set name for
    }
    } catch (e) {
    console.warn(`cannot resolve component name: ${value}`, e);
    }
    }
    }
    }
    }

Leave a comment