从 vuejs 方法返回元素

Elo*_*ati 2 vuejs2 nuxt.js

我对 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>
Run Code Online (Sandbox Code Playgroud)

我的脚本是:

<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>
Run Code Online (Sandbox Code Playgroud)

我想要做的是在某些情况下返回字符串,而在其他一些情况下,例如返回像 h1 这样的 HTML 组件,我似乎无法理解我需要如何执行此操作,或者即使我有正确的为此的方法。

div*_*ine 5

您必须使用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>
Run Code Online (Sandbox Code Playgroud)

您不需要createElement()再使用,只需将 html 代码作为stringor返回即可template string

if (/(ban)$/g.test(value)) {
    return `<h1>${ value }</h1>`; //problem solved
 } else {
    return value
 }
Run Code Online (Sandbox Code Playgroud)

v-html阅读文档中的更多详细信息 https://v2.vuejs.org/v2/guide/syntax.html#Raw-HTML