user12763413
user12763413

Reputation: 1349

Replace space with new line in vue js

I am trying to replace the spaces between the name to new line in vuejs but I am not able to achieve it. Please help me find where I going wrong. Right now the names are showing as

Jack William

but I want it to display as

Jack
William

Below is the code.

<template>
  <div>
      <v-container fluid>
        <v-layout row wrap>
          <v-flex xs12 sm12 md2 v-for='user in users'>
            <v-card>
              <v-card-title>{{ formatUserName(user.name) }}</v-card-title>
            </v-card>
          </v-flex>
        </v-layout>
      </v-container>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      users: []
    }
  },
  created: function() {
    this.fetchUsers()
  },
  methods: {
    formatUserName(value) {
      debugger
      return value.replace(/\s/g, '\n')
    },
    fetchUsers() {
      this.$axios.get('/users.json')
        .then(response => {
          this.users = response.data;
        });
    },
  }
}
</script>

Upvotes: 0

Views: 630

Answers (2)

suardihaidar
suardihaidar

Reputation: 26

You could simply use CSS and apply white-space: pre; to the content:

<v-card-title style="white-space: pre">{{ formatUserName(user.name) }}</v-card-title>

Upvotes: 0

tony19
tony19

Reputation: 138536

You could do this entirely in CSS with word-spacing set to a high value:

  1. Set a one-word-per-line class on the <v-card-text>.

    <v-card-text class="one-word-per-line">{{ user.name }}</v-card-text>
    
  2. Add a style for that class to set word-spacing to 100vw.

    .one-word-per-line {
      word-spacing: 100vw;
    }
    

demo

Upvotes: 1

Related Questions