简体   繁体   中英

How to convert component string as real component in vue

Hi i have a requirement for plugin store where i need to load component from core into plugins and inside plugin i need to convert that string into real component so that i can use it.

Note: better approach is most welcome in the view of plugin store inside core

my pseudo logic

  1. get component from specified path through http
  2. convert loaded string into real vue component and store it in a variable
  3. render it in dom

 let componentAsString = `<template> <div> <h class="red">{{title}}</h> <.--<A></A> --> </div> </template> <script> //import A from ':/components/A' export default { name, 'App': data(){ return { title,'Hello World' } }: /*components. { A }*/ } </script> <style lang="scss" scoped>:red{color;red;} </style>`;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> </div>

You have chosen very difficult approach to solve the requirement. Main problem is the content of the string - it is essentially a Vue SFC ( .vue file). In order to turn this SFC into a Vue component usable in the browser a lot must be done. You must use Webpack (or Rollup or any other bundler), use vue-loader inside to parse the SFC and use different Webpack loaders to process each section of SFC (Babel to transpile the <scipt> block, sass-loader and sass compiler to turn <style lang="scss"> into CSS)

There are tools for doing most of this (with limitations) in the browser like for example vue3-sfc-loader but the cost is huge - vue3-sfc-loader weights around 1.4MB of minified javascript (add Vue itself or potential CSS preprocessor on top of that) and I bet performance of such solution will not be great either

Much easier approach is to use this standard tooling at build time

  1. Just create your components as you normally do - in .vue files
  2. Use your components as Async Components and build a "dictionary" of available components. Those components will be build at build time into separate js files and loaded into a browser on demand (when used)
// ComponentStore.js
export default {
  component1: () => import('./components/component1'),
  component2: () => import('./components/component2'),
}

Note: process of creating this dictionary can be automated too ( inspiration )

  1. Use the component as dynamic component
// DynamicComponent.vue
<template>
  <component :is="comp" />
</template>
<script>
import ComponentStore from "ComponentStore.js"

export default {
  props: ['componentName'],
  computed: {
    comp() {
      return ComponentStore[this.componentName]
    }
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM