【问题标题】:How to render objects inside a string vue2如何在字符串 vue2 中渲染对象
【发布时间】:2017-09-01 16:32:54
【问题描述】:

在 Vue2 中,我的组件中有一个类似于以下行的字符串。

<template>
    <div><h1>Hello World</h1>
    <div v-html="testString"></div>
    </div>
</template>
<script>
    export default {
        name: "test-component",
        props: ['incoming'],        
        data: function() {
            return {
                testString: "";
            }
        },
        created() {
            this.testString = this.incoming;
        }
    }
</script>

然后当我执行以下操作时(正确完成所有导入)

<template>
    <text-component :incoming="mycontent"></text-component>
</template>
<script>
import 'test-component' from './path/to/test-component.vue'
export default { // etc, just presume this bit is right, it's only psudo code
components: ['test-component'],
data() { return { mycontent: '' }},
created() {
    this.mycontent="I just want to <router-link to='/home' v-html='Go Home'></router-link>"
</script>

所以现在我想要第一个带有 testString 的模板来渲染 ,就好像我直接把它放在自己里面一样。

我在我的测试组件中尝试过 v-html{{ }} ,但我认为我遗漏了一些东西。我很确定在 Vue1 中我会使用 {{{ }}}

有人可以帮忙吗?谢谢。

【问题讨论】:

  • 应该是 .... 它是 router-link 从我正在努力处理的字符串中传递的。
  • 在这种情况下,请使用帖子左下角的编辑链接更新问题

标签: javascript vue.js vuejs2 vue-router


【解决方案1】:

来自documentation on v-html

请注意,内容是以纯 HTML 形式插入的——它们不会被编译为 Vue 模板。


您应该改用slot

将插槽添加到您的 testComponent:

<template>
  <div><h1>Hello World</h1>
  <slot></slot>
</template>

然后只需将内容放在test-component 标签中即可:

<template>
  <test-component>
    I just want to <router-link to='/home' v-html='Go Home'></router-link>
  </test-component>
</template>

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2016-11-13
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多