将未转义的HTML传递到vue插槽字符串

时间:2019-05-28 18:35:27

标签: vue.js vuejs2 vue-component

我正在尝试用组件替换现有元素,但是在新组件中使用现有元素数据。

如何将现有元素传递到新的组件插槽中,同时保持原始元素未转义的HTML标记?

document.addEventListener("DOMContentLoaded", function() {
  let ExampleComponent = {
    data: function() {
      return {};
    },
    props: ["type"],
    template: `
            <div>
              <span :class="type">Decoration</span>
              <slot name="myslot">default content</slot>
            </div>
            `
  };

  new Vue({
    el: "#app",
    components: {
      example: ExampleComponent
    },
    data() {
      return {};
    },
    methods: {
      addExampleComponent: function() {
        let target = this.$el.querySelector(".example-target");

        let ComponentClass = Vue.extend(ExampleComponent);
        let instance = new ComponentClass({
          propsData: { type: "primary" }
        });
        instance.$slots.myslot = target.outerHTML;
        instance.$mount();

        target.replaceWith(instance.$el);
      }
    }
  });
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>

  <div id="app">
    <div class="example-target">replace me!</div>
    <div>
      <button v-on:click="addExampleComponent">Replace</button>
    </div>
  </div>

当前,replace me!元素中的"example-target"在按下“替换”按钮后立即显示Decoration <div class="example-target">replace me!</div>。我希望保持HTML完整无缺。

1 个答案:

答案 0 :(得分:1)

尝试使用v:html指令。

    document.addEventListener('DOMContentLoaded', function () {
        let ExampleComponent = {
            data: function () { return {} },
            props: ['type'],
            template: `
          <div>
            <span :class="type">Decoration</span>
            <slot name="myslot">default content</slot>
          </div>
        `
        }

        new Vue({
            el: '#app',
            components: {
                'example': ExampleComponent
            },
            data() { return {} },
            computed: {
                addExampleComponent: function () {
                    let target = this.$el.querySelector('.example-target')

                    let ComponentClass = Vue.extend(ExampleComponent)
                    let instance = new ComponentClass({
                        propsData: { type: 'primary' }
                    })
                    instance.$slots.myslot = target.outerHTML
                    instance.$mount()

                    return instance.$options.template
                }
            }
        })
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.js"></script>
<body>
    <div id="app">
        <div class="example-target">replace me!</div>
        <div>
            <div v-html="addExampleComponent"></div>
        </div>
    </div>
</body>