【问题标题】:Passing html into Vue component将 html 传递给 Vue 组件
【发布时间】:2017-12-08 23:27:40
【问题描述】:

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

【问题讨论】:

    标签: javascript vue.js components vuejs2


    【解决方案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>
    </div>
    

    如果您想传递多个包含 HTML 的字段,也可以使用 Named Slots

    【讨论】:

      【解决方案2】:

      您可以使用 v-html directive 将原始 html 注入到 Vue 组件中。

      【讨论】:

      • 虽然这可行,但您不会通过这种方式获得任何数据绑定。
      • 你当然可以用 v-html 绑定数据,例如

      • 如何将 html 从使用组件的 html 传递给 mydataVariable?
      【解决方案3】:

      几个月前我在一个项目中遇到了类似的问题。我修复了它以 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>
      

      【讨论】:

        猜你喜欢
        • 2017-12-02
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 2018-06-20
        • 2019-10-07
        • 2016-09-24
        • 2018-09-14
        相关资源
        最近更新 更多