Home > Software engineering >  Vuejs how can i attach html with v-html
Vuejs how can i attach html with v-html

Time:03-27

As we know, we can have any html tag in vuejs via v-html, here in mounted() lifecycle function i want to make a simple link and attach it in to p tag. for example:

<template>
    <p v-html="caption"></p>
</template>

<script>
export default {
    name: "emulator",
    props: {
        caption: {
            type: String,
            required: false
        }
    },
    mounted() {
        this.$emit('caption', this.$el.innerText.replace(
            /#([\p{L}\p{N}_-] )/u,
            '<a href="https://www.instagram.com/explore/tags/$1" target="_blank">$&</a>'
        ))
    }
}
</script>

the this.$emit work fine but i don't have any link into p tag when i try to type for example:

hi #vuejs

it should be: <p><a href="https://www.instagram.com/explore/tags/vuejs" target="_blank">hi #vuejs</a></p>

replace method work fine too and we can test it from this link

CodePudding user response:

I don't know if $emit in this component is necessary but the following works:

<template>
    <p v-html="link"></p>
</template>

<script>
export default  {
    name: "emulator",
    props: {
        caption: {
            type: String,
            default: '#john'
        }
    },
    computed: {
      link(){
        const anchorTag = this.caption.replace(
            /#([\p{L}\p{N}_-] )/u,
            '<a href="https://www.instagram.com/explore/tags/$1" target="_blank">$&</a>'
        )
        this.$emit(anchorTag) // <--- remove this line if you don't need the HTML tag in your parent
        return anchorTag
      }
    }
}
</script>
  • Related