Я пытаюсь заменить символы \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"):



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Из документов 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 (<br>). Не используйте для вывода непроверенного пользовательского ввода или HTML из ненадежного источника. В этих случаях выполните предварительную обработку значения или посмотрите на Ответ Павла Левина оригинальное решение.(?:) вы используете группа без захвата, который вам не нужен в этом случае: в этом случае будет достаточно /\r*\n/g\n (как в представлении JSON), вам нужно сопоставить ее с дополнительной предшествующей обратной косой чертой: тогда ваше регулярное выражение становится: /(\\r)*\\n/gcomputed: {
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><br>, 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>