5

I'm trying to insert line breaks between the spaces of the first item in my array "texts" but .split and .join aren't affecting the output. I'm using Vue cli, gridsome, and tailwindCSS.

Is my approach targeting the spaces between the words in an array to create a new line a valid one, or do I need to rewrite the html and JavaScript loop?

<template>
  <div id="content">
    <transition name="fade" mode="out-in">
      <p class="text-4xl py-3 text-center bg-egg-100 text-white px-3" :key="index">{{ text }}</p>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'Intro',
  computed: {
    text: function() {
      return this.texts[this.index].split(" ").join("\n");
    }
  },
  data() {
    return {
      index: 0,
      texts: [
        'ABC DEF HIJ',
        'Alphabet'
    ]}  
  },
  created() {  
    this.startInterval();
  },
  methods: {
    startInterval: function() {
      setInterval(() => {
        this.index++;
        if (this.index >= this.texts.length)
        this.index = 0;
      }, 3500);
    }
  }  
}
</script>

<style>
#content {
    font-family: 'IPAex明朝';
}

.fade-leave-active {
  transition: opacity 1s ease-in;
  transition-duration: .5s;
}

.fade-enter-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.fade-enter, .fade-leave-to {
  opacity: 0.0;
}

.fade-leave, .fade-enter-to {
  opacity: 1.0;
}
</style>
1
  • Think about how a browser renders HTML typed in by hand. Newlines are treated the same was as simple spaces. Commented Nov 13, 2019 at 2:19

2 Answers 2

4

Newlines and consecutive spaces are ignored in HTML by default. If you want newlines to be rendered then you need to set the white-space CSS style on that element to a value like pre-wrap.

Do not use v-html because this is susceptible to XSS attacks. Always avoid v-html unless you have a good reason to use it.

Sign up to request clarification or add additional context in comments.

Comments

0

This is because you are using the output inside HTML which happens to ignore whitespace characters and boils them down to a single space. To emulate newline, you should do the following:

return this.texts[this.index].split(" ").join("<br/>");

2 Comments

I had to use v-html="text" on the <p> tag, and that was the key to getting <br> to work. Thanks!
Did you try removing all the CSS classes to make sure CSS isn't interfering?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.