return 个来自 vuejs 方法的元素
return elements from a vuejs method
我对 vuejs 有点陌生,我什至不确定我到底在找什么,
我有这个模板:
<template>
<md-content class="md-elevation-2">
<div class="md-layout">
<div class="md-layout-item" v-for="key in ruleData">
{{ getKeyOutput(key) }}
</div>
</div>
</md-content>
</template>
我的脚本是:
<script>
export default {
props: ['ruleData'],
methods: {
getKeyOutput(value) {
switch (typeof value) {
case 'string':
if (/(ban)$/g.test(value)) {
return createElement(`<h1>${ value }</h1>`) // here is the problem
} else {
return value
}
break
case 'number':
return String(value)
break
case 'boolean':
return String(value)
break
default:
return value
break
}
}
}
}
</script>
我想做的是在某些情况下 return 字符串,在其他一些情况下 return 一个 HTML 组件,例如 h1,我不能似乎明白我需要怎么做,或者即使我有正确的方法。
您必须使用 v-html
指令来呈现存储为字符串的 html 标签。
如果你不使用 v-html
那么默认情况下 vuejs 会转义 html 标签,因此 html 标签显示为纯文本。您不需要在代码中的任何地方使用 createElement()
,只需将其删除即可。
如下更改您的 vue 模板代码并验证您是否获得了预期的结果
<div
class="md-layout-item"
v-for="(value,key) in ruleData"
:key="key"
v-html="getKeyOutput(value)">
</div>
您不需要再使用 createElement()
,只需 return html 代码作为 string
或 template string
if (/(ban)$/g.test(value)) {
return `<h1>${ value }</h1>`; //problem solved
} else {
return value
}
在文档中阅读有关 v-html
的更多详细信息 https://vuejs.org/v2/guide/syntax.html#Raw-HTML
我对 vuejs 有点陌生,我什至不确定我到底在找什么, 我有这个模板:
<template>
<md-content class="md-elevation-2">
<div class="md-layout">
<div class="md-layout-item" v-for="key in ruleData">
{{ getKeyOutput(key) }}
</div>
</div>
</md-content>
</template>
我的脚本是:
<script>
export default {
props: ['ruleData'],
methods: {
getKeyOutput(value) {
switch (typeof value) {
case 'string':
if (/(ban)$/g.test(value)) {
return createElement(`<h1>${ value }</h1>`) // here is the problem
} else {
return value
}
break
case 'number':
return String(value)
break
case 'boolean':
return String(value)
break
default:
return value
break
}
}
}
}
</script>
我想做的是在某些情况下 return 字符串,在其他一些情况下 return 一个 HTML 组件,例如 h1,我不能似乎明白我需要怎么做,或者即使我有正确的方法。
您必须使用 v-html
指令来呈现存储为字符串的 html 标签。
如果你不使用 v-html
那么默认情况下 vuejs 会转义 html 标签,因此 html 标签显示为纯文本。您不需要在代码中的任何地方使用 createElement()
,只需将其删除即可。
如下更改您的 vue 模板代码并验证您是否获得了预期的结果
<div
class="md-layout-item"
v-for="(value,key) in ruleData"
:key="key"
v-html="getKeyOutput(value)">
</div>
您不需要再使用 createElement()
,只需 return html 代码作为 string
或 template string
if (/(ban)$/g.test(value)) {
return `<h1>${ value }</h1>`; //problem solved
} else {
return value
}
在文档中阅读有关 v-html
的更多详细信息 https://vuejs.org/v2/guide/syntax.html#Raw-HTML