将 html 传递给 Vue 组件

新手上路,请多包涵

目前我将一些参数传递给 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。

原文由 LeBlaireau 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 593
1 个回答

不要使用属性传递 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>
>
> ```

> 以及使用该组件的父母:

> ```
>  <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>
>
> ```

”`

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

原文由 str 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题