将 html 传递给 Vue 组件 [英] Passing html into Vue component

查看:46
本文介绍了将 html 传递给 Vue 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 <滑块:images="['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']":html="['<div>你好</div>', '<div>再见</div>']"</滑块>

滑块是html"滑块或带有图像的滑块.

虽然我传入的 html 会变得更加复杂,可能有 30 行,但作为参数将更难阅读和管理.

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

<div class="work-slide">{{ content }}</div>

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

解决方案

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

<块引用>

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

<h2>我是孩子的头衔</h2><插槽>只有在没有内容时才会显示分发.</slot>

以及使用该组件的父级:

<h1>我是父标题</h1><我的组件><p>这是一些原创内容</p><p>这是一些更原创的内容</p></my-component>

渲染结果为:

<h1>我是父标题</h1><div><h2>我是孩子的头衔</h2><p>这是一些原创内容</p><p>这是一些更原创的内容</p>

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

At the moment I pass some parameters into a vue component

 <Slider
      :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']"
      :html="['<div>hello</div>', '<div>goodbye</div>']"
    </Slider>

The slider is either an 'html' slider or one with images.

This works fine although the html I pass in is going to get a lot more complex, maybe 30 lines and this will be harder to read and manage as params.

Can I pass in an external reference and pull that into the component?

<div v-for="content in html">
    <div class="work-slide">{{ content }}</div>
</div>

As you can see the loop in the component is a very simple v-for.

解决方案

Don't pass HTML using attributes but using Slots:

Suppose we have a component called my-component with the following template:

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

And a parent that uses the component:

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

The rendered result will be:

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

You can also use Named Slots if you want to pass more than one field containing HTML.

这篇关于将 html 传递给 Vue 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆