M Fukazawa
M Fukazawa

Reputation: 63

.join("\n") not creating a new line in JavaScript array using Vue CLI

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>

Upvotes: 5

Views: 5506

Answers (2)

Decade Moon
Decade Moon

Reputation: 34286

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.

Upvotes: 4

Faisal Rahman Avash
Faisal Rahman Avash

Reputation: 1256

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/>");

Upvotes: 0

Related Questions