skip to Main Content

I need compile custom vue js script and render it on page

Example:

let js = `"Hello, please choose your variant:<br /> <pool :id='144'>"`
const component = Vue.compile(js)

After (for example):

<div class="user-post">
<component :is="component" />
</div>

How i can implement this with vue?

2

Answers


  1. Chosen as BEST ANSWER

    Solution:

    const component = defineComponent({
      components: {Pool},
      template: '<div>Hello, please choose your variant:<br /> <pool :id='144'></div>'
    })
    

    After

    <div class="user-post">
    <component :is="component" />
    </div>
    

  2. Vue SFC Playground

    You need several things here:

    1. Compile your HTML to a component with compile(). Note that for that you need a different Vue build in vite.config.js (see below).
    2. To make your components available in the new component, assign components property to, so the Vue would know components used in the original HTML.
    3. If you need some variables used as props use v-bind.
    <script setup>
    import Pool from './Pool.vue';
    import {compile, ref} from 'vue';
    
    const id = ref('144');
    
    const component = Object.assign(
      compile(`"Hello, please choose your variant:<br /> <pool :id='id'/>"`), {
        components: { Pool }
      });
    
    </script>
    
    <template>
      <component v-bind="{id}"/>
      <br/>
      <input v-model="id">
    </template>
    

    vite.config.js

    import { fileURLToPath, URL } from 'node:url'
    
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    // https://vitejs.dev/config/
    export default defineConfig({
        plugins: [
            vue(),
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
                vue: 'vue/dist/vue.esm-bundler.js',
            }
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search