[英]How to convert array of tags as text wrappers from js code to vue?
I have this js code:我有这个js代码:
var tags = [
'b',
'i'
'u',
];
var text = 'some simple text';
tags.forEach(tag => {
text = '<' + tag + '>' + text + '</' + tag + '>';
});
//print wrapped "text" variable on the page (Upd:) like: <b><i><u>Some text</u></i></b>
How to convert this to vue component/template?如何将其转换为 vue 组件/模板?
You have two options:你有两个选择:
<div v-html="xxx" />
Docs: https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML <div v-html="xxx" />
Docs: https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML In Your case first option is better choice.在您的情况下,第一个选择是更好的选择。 Dynamics components are actually designed for Vue components, not raw html tags - but it's possible to use them this way if You really need to.
Dynamics 组件实际上是为 Vue 组件设计的,而不是原始的 html 标记 - 但如果您确实需要,可以以这种方式使用它们。
Create a computed property called tagged
and render it inside the template using v-html
directive:创建一个名为
tagged
的计算属性,并使用v-html
指令将其呈现在模板中:
var app=new Vue({ el: "#app", data() { return { text: "some text" }; }, computed: { tagged() { var tags = [ 'b', 'i', 'u', ]; tags.forEach(tag => { this.text = '<' + tag + '>' + this.text + '</' + tag + '>'; }); return this.text; } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-html="tagged"></div> </div>
Second solution is to create a component with the 3 tags and pass the text as prop:第二种解决方案是创建一个带有 3 个标签的组件并将文本作为道具传递:
Vue.component('bui-tag', { props: ['text'], template: `<b><u><i>{{text}}</i></u></b>` }) var app = new Vue({ el: "#app", data() { return { text: "some text" }; }, computed: { tagged() { var tags = [ 'b', 'i', 'u', ]; tags.forEach(tag => { this.text = '<' + tag + '>' + this.text + '</' + tag + '>'; }); return this.text; } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <bui-tag:text="text" /> </div>
The acceptability of v-html
depends on the source of markup data. v-html
的可接受性取决于标记数据的来源。 It shouldn't be used with unsanitized, user-defined HTML, doing this is dangerous and may result in script injections.它不应该与未经处理的、用户定义的 HTML 一起使用,这样做很危险并且可能导致脚本注入。
This is the case for render function , it allows to build a hierarchy of tags that will be rendered into DOM elements:渲染 function就是这种情况,它允许构建将被渲染到 DOM 元素中的标签层次结构:
export default {
render(h) {
return tags.reduceRight(
(wrapper, tag) => h(tag, [wrapper]),
text
);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.