Заменить \n на новую строку на vuejs

Я пытаюсь заменить символы \n на новую строку данных, которая поступает из конечной точки.


Пробовал <p>{{ item.licensedocument.legal.documentText.replace(/(?:\r\n|\r|\n)/g, '<br />') }}</p> не получилось. Фигурные скобки перестали работать и никогда не действовали как JS, когда я пишу replace() в конец задачи. Вывод такой:

    {{ item.licensedocument.legal.documentText.replace(/(?:\r\n|\r|\n)/g, '
') }}

Когда я пишу просто <p>{{ item.licensedocument.legal.documentText }}</p>, это работает, и вывод похож на

GENERAL SERVICE AGREEMENT\n\nTHIS GENERAL SERVICE AGREEMENT (the "Agreement") dated this 22nd day of June, 2018\nBETWEEN:\nCLIENT\n______________________\n______________________________\nCONTRACTOR\n______________________\n______________________________\nBACKGROUND\nThe Client is of the opinion that the Contractor has the necessary qualifications, experience and abilities to provide services to the Client.\nThe Contractor is agreeable to providing such services to the Client on the terms and conditions set out in this Agreement.\nIN CONSIDERATION OF the matters described above and of the mutual benefits and obligations set forth in this Agreement, the receipt and sufficiency of which consideration is hereby acknowledged, the Client and the Contractor (individually the "Party" and collectively the "Parties" to this Agreement) agree as follows:\n\nSERVICES PROVIDED \nThe Client hereby agrees to engage the Contractor to provide the Client with the following services (the "Services"):

Я также попытался добавить такой метод, как:

 methods: {
    handleNewLine(str) {
      return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
    },
  },

И вызвал функцию как: <p>{{ handleNewLine(item.licensedocument.legal.documentText) }}</p> И вывод был таким же:

GENERAL SERVICE AGREEMENT\n\nTHIS GENERAL SERVICE AGREEMENT (the "Agreement") dated this 22nd day of June, 2018\nBETWEEN:\nCLIENT\n______________________\n______________________________\nCONTRACTOR\n______________________\n______________________________\nBACKGROUND\nThe Client is of the opinion that the Contractor has the necessary qualifications, experience and abilities to provide services to the Client.\nThe Contractor is agreeable to providing such services to the Client on the terms and conditions set out in this Agreement.\nIN CONSIDERATION OF the matters described above and of the mutual benefits and obligations set forth in this Agreement, the receipt and sufficiency of which consideration is hereby acknowledged, the Client and the Contractor (individually the "Party" and collectively the "Parties" to this Agreement) agree as follows:\n\nSERVICES PROVIDED \nThe Client hereby agrees to engage the Contractor to provide the Client with the following services (the "Services"):

Я также вызываю как <p v-html = "handleNewLine(item.licensedocument.legal.documentText)"></p> и <p v-html = "item.licensedocument.legal.documentText.replace(/(?:\r\n|\r|\n)/g, '<br />')"></p>, и replace() все еще не работает. Выход:

GENERAL SERVICE AGREEMENT\n\nTHIS GENERAL SERVICE AGREEMENT (the "Agreement") dated this 22nd day of June, 2018\nBETWEEN:\nCLIENT\n______________________\n______________________________\nCONTRACTOR\n______________________\n______________________________\nBACKGROUND\nThe Client is of the opinion that the Contractor has the necessary qualifications, experience and abilities to provide services to the Client.\nThe Contractor is agreeable to providing such services to the Client on the terms and conditions set out in this Agreement.\nIN CONSIDERATION OF the matters described above and of the mutual benefits and obligations set forth in this Agreement, the receipt and sufficiency of which consideration is hereby acknowledged, the Client and the Contractor (individually the "Party" and collectively the "Parties" to this Agreement) agree as follows:\n\nSERVICES PROVIDED \nThe Client hereby agrees to engage the Contractor to provide the Client with the following services (the "Services"):

Только что нашел пакет npm с именем Nl2br, но он все еще не работает. Выход такой же:

GENERAL SERVICE AGREEMENT\n\nTHIS GENERAL SERVICE AGREEMENT (the "Agreement") dated this 22nd day of June, 2018\nBETWEEN:\nCLIENT\n______________________\n______________________________\nCONTRACTOR\n______________________\n______________________________\nBACKGROUND\nThe Client is of the opinion that the Contractor has the necessary qualifications, experience and abilities to provide services to the Client.\nThe Contractor is agreeable to providing such services to the Client on the terms and conditions set out in this Agreement.\nIN CONSIDERATION OF the matters described above and of the mutual benefits and obligations set forth in this Agreement, the receipt and sufficiency of which consideration is hereby acknowledged, the Client and the Contractor (individually the "Party" and collectively the "Parties" to this Agreement) agree as follows:\n\nSERVICES PROVIDED \nThe Client hereby agrees to engage the Contractor to provide the Client with the following services (the "Services"):
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
14
1
15 989
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Из документов Vue на Интерполяция необработанного HTML:

The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the v-html directive

<p v-html = "item.licensedocument.legal.documentText.replace(/(?:\r\n|\r|\n)/g, '<br />')"></p>

или, при использовании вашего метода:

<p v-html = "handleNewLine(item.licensedocument.legal.documentText)"></p>
Ответ принят как подходящий
  • Вы должен действительно использоватьv-html, потому что при использовании {{ var }} ваши <br> будут видны как объекты HMTL (&lt;br&gt;). Не используйте для вывода непроверенного пользовательского ввода или HTML из ненадежного источника. В этих случаях выполните предварительную обработку значения или посмотрите на Ответ Павла Левина оригинальное решение.
  • Ваше регулярное выражение излишне сложно. С (?:) вы используете группа без захвата, который вам не нужен в этом случае: в этом случае будет достаточно /\r*\n/g
  • Если вы получаете текстовую строку буквально со вставленной обратной косой чертой \n (как в представлении JSON), вам нужно сопоставить ее с дополнительной предшествующей обратной косой чертой: тогда ваше регулярное выражение становится: /(\\r)*\\n/g
  • Использование такого метода, как вы, прекрасно, но вы также можете использовать вычисление:
computed: {
  withBrTags: function() {
    const doc = this.item.licensedocument.legal.documentText
    return doc.replace(/(\\r)*\\n/g, '<br>')
  }
}

Использование v-htmlопасный, использование methods и так далее бессмысленно.

На самом деле все просто:

Использование в CSS

.text-block {
    white-space: pre; // or pre-line
}

в Vue/Nuxt/JavaScript используйте string + \n

data: {
   text: 'Lorem ipsum dolor sit amet, \n consectetur adipisicing elit. \n Consequatur, nesciunt?'
}

в шаблоне .vue

<div class = "text-block">
    {{ text }}
</div>

если вы просто хотите заменить символы \n на новую строку, вы можете просто использовать CSS со свойством white-space.

.white-space {
  width: 200px;
  margin: 10px;
  border: 1px solid red;
  
  span {
    color: red;
  }
}

.pre-line {
  white-space: pre-line;
}
<div class = "white-space pre-line">
  <span>pre-line</span>
      Sequences of white space are collapsed    .
  Lines are broken at newline characters, at <br>&lt;br&gt;, and as necessary to fill line boxes.
</div>

Вам следует избегать v-html. Лучший способ реализовать вывод разрывов строк — использовать директивы

var app = new Vue({
  el: '#app',
  data() {
    return {
      value: ' Text with break line.\n Next line.',
      value2: `Text with break line.
               Next line.`
    }
  },
  directives: {
    nl2br: {
      inserted(el) {
        // simplified example, 
        // works only for nodes without any child elements
        el.innerHTML = el.textContent.replace(/\n/g, '<br />')
      }
    }
  }
})
<script src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id = "app">
  <p v-nl2br>{{ value }}</p>
  <p v-nl2br>{{ value2 }}</p>
</div>

Другие вопросы по теме