将HTML传递到Vue组件中

19

目前我将一些参数传递给Vue组件

 <Slider
      :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']"
      :html="['<div>hello</div>', '<div>goodbye</div>']"
    </Slider>
滑块可以是一个“html”滑块或带有图像的滑块。
尽管我传递的html将变得更加复杂,可能有30行,但这很好用。由于参数难以阅读和管理,因此这将更加困难。
我能否传入外部引用并将其拉到组件中?
<div v-for="content in html">
    <div class="work-slide">{{ content }}</div>
</div>

正如你所看到的,该组件中的循环非常简单,使用了v-for指令。

3个回答

35

不要使用属性传递 HTML,而是使用插槽

假设我们有一个名为 my-component 的组件,具有以下模板:

<div>
  <h2>I'm the child title</h2>
  <slot>
    This will only be displayed if there is no content
    to be distributed.
  </slot>
</div>

一个使用该组件的父组件:

<div>
  <h1>I'm the parent title</h1>
  <my-component>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </my-component>
</div>
渲染的结果将是:
<div>
  <h1>I'm the parent title</h1>
  <div>
    <h2>I'm the child title</h2>
    <p>This is some original content</p>
    <p>This is some more original content</p>
  </div>
</div>

如果您想传递包含HTML的多个字段,还可以使用命名插槽


5
你可以使用 v-html指令 将原始的html注入到Vue组件中。

虽然这样做可以工作,但你无法获得任何数据绑定。 - Thomas Kilkelly
1
你可以使用 v-html 绑定数据,例如: <p v-html="mydataVariable"></p>。 - David Mold
我该如何将使用组件的HTML传递给mydataVariable? - Fanky

1
我曾在几个月前的一个项目中遇到类似的问题。我通过以base64格式传递HTML代码来解决它。
我的父组件:
<wysywyg id="ssaasa" :bal="to64('<strong>Me</strong>')"></wysywyg>

我的方法:

methods: {
        to64(html) {
            return btoa(html)
        }
    }

我的组件:

<template>
    <div class="RenderHTMLEditor mx-3">
        <label class="subtitle-1 pb-3">{{label}}</label>
        <textarea html="true" v-model="to64"
        width="100%"
        :style="'height:'+height+'px;'"
        wysywyg="true"
        :name="id" :id="id"
        class="tinywy">
        </textarea>
    </div>
</template>

<script>
export default {
    props: ['label', 'id', 'height', 'bal'],
    data: function() {
        return {
            
        }
    },
    computed: {
        to64: function() {
            return atob(this.bal)
        }
    },
    mounted: function() {
        window.initWy(this.id)
    }
}
</script>

<style scoped>
.RenderHTMLEditor {
    width: 100%;
}
</style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接