我需要编译自定义 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 实现这个?
这里你需要几样东西:
compile()
将 HTML 编译为组件。请注意,为此您需要在 vite.config.js 中构建不同的 Vue(见下文)。components
属性,以便 Vue 知道原始 HTML 中使用的组件。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',
}
}
})
解决方案:
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>