0

I have a situation, where my Vue component renders html (it comes from database) this way:

  <div
          id="post-body-text"
          class="post__main-text"
          v-html="postText"
        ></div>

Now inside this HTML, there may be iframes which I would like to wrap in divs, with special styling (to make the iframe size dynamic)

What would be the Vue way to do this? Because the only option that I can find is document.createlement("div") and then doing the native javascript stuff. Which doesn't work, I guess it is related to component rerendering

r.Die
  • 125
  • 3
  • 14

1 Answers1

0

Your approach is almost correct: all you need to do is to use a computed property for v-html, so that you can do all the parsing in the computed property:

new Vue({
  el: '#app',
  data: {
    postText: '<h2>Hello world</h2><iframe></iframe><p>Lorem ipsum</p>'
  },
  computed: {
    parsedPostText() {
      const el = document.createElement('div');
      el.innerHTML = this.postText;
      el.querySelectorAll('iframe').forEach(iframe => {
        // Wrapper logic adapted from
        // https://stackoverflow.com/a/57377341/395910
        const wrapper = document.createElement('div');
        iframe.parentNode.insertBefore(wrapper, iframe);
        wrapper.appendChild(iframe);
      });
      return el.innerHTML;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="post-body-text" class="post__main-text" v-html="parsedPostText"></div>
</div>
Terry
  • 63,248
  • 15
  • 96
  • 118