【问题标题】:Use JSON value as HTML tag with vue使用 JSON 值作为带有 vue 的 HTML 标记
【发布时间】:2019-04-15 00:33:39
【问题描述】:

我有一个输出以下样式的 JSON 文件:

{
"h1" : {
    "font-family" : "Lato",
    "font-size" : "24px",
    "line-height" : "28px",
    "font-weight" : 600,
    "colorId" : 3,
    "margin-bottom" : "10px",
    "margin-top" : "20px"
},
"h2" : {
    "font-family" : "Lato",
    "font-size" : "20px",
    "line-height" : "24px",
    "font-weight" : 600,
    "colorId" : 3,
    "margin-bottom" : "10px",
    "margin-top" : "20px"
}

}

我想使用第一个键“h1, h2, ...”作为 HTML 标记来显示它。 Vue 可以做到这一点吗?

应该是这样的:

<div v-for="(props, tag) in headers">
    <{{ tag }}>x</ {{ tag }}>
</div>

【问题讨论】:

    标签: html json parsing vue.js


    【解决方案1】:
    <div v-for="(props, tag) in headers" v-html="`<${tag}>x</${tag}>`"></div>
    

    【讨论】:

    • 太好了!谢谢。添加样式怎么样?
    • 这种方式不可能绑定任何属性。您将静态 html 字符串传递给“v-html”。但是您可以添加一个构建 html 的函数。
      buildHtml(props, tag) { return &lt;${tag} + Object.keys(props) .reduce((total, key) => { return total + `${key}:${props[key]}); +&gt; + x +&lt;${tag}&gt; }
    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多