Home > Net >  How can I insert a line break , render html for text in VUE?
How can I insert a line break , render html for text in VUE?

Time:06-28

I got a string coming to frontend like this comeoutside

But in html I need to render this with a condition

const separateFirstFourWords = (words) => {
  let newStr = `${words.substring(0, 4)} <br> ${words.substring(4,words.length)}`;
  return newStr;
};

<p>{{something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')}}</p>

As you can see I wanna separate the two words and want a line break between these words how can I achieve that in VUE

CodePudding user response:

You could use the v-html directive for that:

<p v-html="something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')"></p>

This will render the outcome of the ternary operator as HTML.

Be aware of the cross site scripting vulnerabilities this might create, though, see warning in v-html documentation.

CodePudding user response:

You can use v-html :

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const separateFirstFourWords = (words) => {
      let newStr = `${words.substring(0, 4)} <br> ${words.substring(4, words.length)}`;
      return newStr;
    };
    const something = ref(true)
    return { separateFirstFourWords, something }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <p v-html="something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')"></p>
  <button @click="something = !something">change something</button>
</div>

CodePudding user response:

Why not use v-if? That way your app will be safe against HTML/JS injections.

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const words = 'comeoutside'
    const something = ref(false)
    return { words, something }
  }
})
app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
    <div v-if="something"><p>{{words}}</p></div>
    <div v-else>
    <p>{{words.substring(0, 4)}}
    <br/>
    {{words.substring(4, words.length)}}</p>
    </div>
</div>

  • Related