将html传递给Vue组件

LeB*_*eau 6 javascript components vue.js vuejs2

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

 <Slider
      :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']"
      :html="['<div>hello</div>', '<div>goodbye</div>']"
    </Slider>
Run Code Online (Sandbox Code Playgroud)

滑块是'html'滑块或带图像的滑块.

这很好用,虽然我传入的html会变得更复杂,可能是30行,这将更难以阅读和管理作为参数.

我可以传入外部引用并将其拉入组件吗?

<div v-for="content in html">
    <div class="work-slide">{{ content }}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,组件中的循环是一个非常简单的v-for.

str*_*str 14

不要使用属性传递HTML,而是使用Slots:

假设我们有一个名为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>
Run Code Online (Sandbox Code Playgroud)

以及使用该组件的父级:

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

渲染结果将是:

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

如果要传递包含HTML的多个字段,也可以使用命名槽.


小智 6

You can inject raw html into Vue components with the v-html directive.