Vue 使用子组件编译并渲染 HTML

问题描述 投票:0回答:2

我需要编译自定义 vue js 脚本并将其渲染在页面上

示例:

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

之后(例如):

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

我如何用 vue 实现这个?

javascript vue.js
2个回答
1
投票

Vue SFC 游乐场

这里你需要几样东西:

  1. 使用
    compile()
    将 HTML 编译为组件。请注意,为此您需要在 vite.config.js 中构建不同的 Vue(见下文)。
  2. 要使您的组件在新组件中可用,请分配
    components
    属性,以便 Vue 知道原始 HTML 中使用的组件。
  3. 如果您需要一些变量用作道具,请使用
    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',
        }
    }
})

0
投票

解决方案:

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

之后

<div class="user-post">
<component :is="component" />
</div>
© www.soinside.com 2019 - 2024. All rights reserved.