Andrew See
Andrew See

Reputation: 1122

How to use vuetify's v-img inside v-html

I would like to use <v-img> of vuetify inside v-html to replace the standard <img>, i.e.

<div v-html="'<v-img src="some_image_url" />'">

I understand that v-html is meant for only standard HTML component, and I would like to know if there is anyway to use a custom component (such as <v-img>) inside v-html.

Upvotes: 3

Views: 3408

Answers (2)

Andrew See
Andrew See

Reputation: 1122

I managed to solve it with v-runtime-template, which can be found here:

https://github.com/alexjoverm/v-runtime-template

Cheers!

Upvotes: 1

skirtle
skirtle

Reputation: 29132

The example below uses some cheap and cheerful RegExps to do the parsing, nothing I would use in production code. My focus was on how to avoid using v-html rather than finding a reliable way to parse out the <img> tags.

The key thing I'm trying to demonstrate is how you can parse the text into chunks and then iterate over the chunks in the template to create v-img components. I've used a dummy component for v-img but the principle would be exactly the same for the real thing.

new Vue({
  el: '#app',
  
  components: {
    vImg: {
      template: '<strong>[<slot/>]</strong>'
    }
  },
  
  data () {
    return {
      text: 'Something something <img src="somepath"> and <img src="otherpath">'
    }
  },
  
  computed: {
    chunks () {
      const re = /(<img\s[^>]*>)/g
      const text = this.text
      const parts = text.split(re).filter(part => part)

      return parts.map(part => {
        if (part.match(re)) {
          const matchSrc = part.match(/\ssrc="([^"]*)"/)
          
          return {
            src: matchSrc && matchSrc[1]
          }
        }
        
        return part
      })
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <template v-for="chunk in chunks">
    <template v-if="typeof chunk === 'string'">{{ chunk }}</template>
    <v-img v-else>{{ chunk.src }}</v-img>
  </template>
</div>

Upvotes: 1

Related Questions