首页 > 解决方案 > 如何将 HTML 代码分配给 Vue.js 中的变量

问题描述

我想在我的 Vue.js 3setup()函数中的变量中包含一些 HTML,以便稍后在模板中使用。

当我尝试以下操作时,我收到一个错误,"VueCompilerError: Invalid end tag."因为 Vue 似乎认为它是组件代码的一部分(当然不是)。

<script>
imports...

setup() {

const a = a;
const b = b;

const MyHTML = '<script></script>'  // Vue thinks the </script> tag is part of the code
}
</script> // This gets thrown an error of VueCompilerError: Invalid end tag.

然后,如何在不被 Vue 解释的情况下将 HTML 作为字符串存储在变量中?

标签: javascriptvue.jsvuejs3

解决方案


我对此进行了搜索并找到了几种解决方案。解决方案之一是在线下方。我认为这是最好的解决方案

<div v-html="MyHTML"></div>  
// eslint-disable-next-line no-useless-escape
const MyHTML = ref('<script><\/script>')

另一个有趣的解决方案是

const MyHTML = '...... </scr'+'ipt>......';

推荐阅读