将包含组件的字符串解析为 vue.js 中的模板 [英] Parse string with components inside to template in vue.js

查看:140
本文介绍了将包含组件的字符串解析为 vue.js 中的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 vue.js 中将包含组件的字符串解析为模板?字符串示例:

"一些文字,一些<b>粗体</b>,以及从这里插入的图像组件 <vue-simple-image :src='images/my_image_name.png'/>, 另一个 text 和 html 标签."

看起来我需要将这些字符串存储到数据库中,以便以后使用它们从 vue-wysiwyg 编辑器重新创建用户输入.

解决方案

从严格意义上讲,您提出的问题,我认为这是不可能的.有一个 v-html 指令,它可以为你呈现 html 而不是组件.这也被认为是一种反模式,正如 vue 指南所述:

<块引用>

在您的网站上动态渲染任意 HTML 可能非常危险,因为它很容易导致 XSS 攻击.仅在受信任的内容上使用 v-html,切勿在用户提供的内容上使用.

您可以查看 动态组件 以呈现 vue基于用户输入的组件.您可以解析所见即所得的用户输入,在已识别的 vue-component 标签上拆分字符串(这样您就有了一系列元素,其中包含常规 html 序列和单个 vue-components 元素),然后使用带有 v- 的模板for 循环来呈现这个.(非工作伪代码)示例:

<div v-for="splitInput 中的元素"><component v-if="stringIsVueComponent(element)" v-bind:is="element"></component><div v-else v-html="元素"></div>

尽管要考虑在 vue 组件本身内部输入的可能性,例如如果您正在填充插槽,您将不得不更多地解决此示例.我会尽量限制您要支持的输入类型,以使其易于管理.

Is it possible to parse string with components inside to template in vue.js? Example of string:

"Some text, some <b>bold text</b>, and inserted image from this 
component <vue-simple-image :src='images/my_image_name.png' />, another text and html tags."

It looks like I need store such strings to database to use them later for recreating user input from vue-wysiwyg editor.

解决方案

In the strict sense you asked the question, I do not think this is possible. There is a v-html directive, that can render html for you but not components. This is also considered an anti-pattern, as the vue guide states:

Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS attacks. Only use v-html on trusted content and never on user-provided content.

You could look into dynamic components in order to render vue components based on user input. You could parse the wysiwyg user input, split the string on recognized vue-component tags (so you have an array of pieces of elements with sequences of regular html and elements that are single vue-components), and then use a template with v-for looping to render this. (non-working pseudocode) example:

<div id="renderedWysiwygInput">
  <div v-for="elem in splitInput">
   <component v-if="stringIsVueComponent(element)" v-bind:is="element"></component>
   <div v-else v-html="element"></div>
  </div>
</div>

You'll have to work this example out a bit more though to account for the possibility of input inside the vue components themselves, for example if you are filling slots. I would try to limit what kind of input you are going to support to keep it manageable.

这篇关于将包含组件的字符串解析为 vue.js 中的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆