在运行时将 HTML 转换为 Vue 组件

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

我正在学习 Vue,并且正在构建一个简单的 wiki 页面。原始文章数据是用自定义标记编写的 JSON 文件。例如,以下标记:

The ''sun'' is {r=black black}
应该这样“编译”:
<p>The <b>sun</b> is <Ref path="/black">black</p>
我可以使用正则表达式和字符串操作来完成此操作,但我无法使用该字符串作为模板选项,因为它仅适用于静态输入。如果它只是 html,我可以使用 v-html 指令或其他相关的指令。 我的模板获取 JSON 文件并根据我选择的标准解析我的自定义标记。它从中得到的是一个字符串(Vue 标记)不能分配给“模板”选项,因为它只接受静态字符串并且不识别任何变量。

我尝试将已编译的 vue 标记或使用运行时编译器的模板选项分配给模板选项。也许我错了。我该怎么办?

javascript vue.js markup
1个回答
1
投票

您可以使用

compile()
编译 vue 模板,然后使用
<Component>
插入到当前模板中。另外,我们需要在 vite.config.js 中将别名“vue”导入更改为“vue/dist/vue.esm-bundler.js”以启用此功能。

更改的文件来自

npm create vue@latest
:

应用程序.vue

<script setup>

import { ref, compile } from 'vue';

const msg = ref('Hello world!');
const component = ref(compile('<HelloWorld :msg="msg"></HelloWorld>'));

</script>

<template>
    <main>
        <Component :is="component" :msg="msg"></Component>
    </main>
</template>

main.js

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'


const app = createApp(App);
import HelloWorld from './components/HelloWorld.vue'
app.component('HelloWorld', HelloWorld);
app.mount('#app')

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',
        }
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.