Last active
March 17, 2023 10:19
-
-
Save codeflorist/aad1313643f2a529f34b7b81b0b865f8 to your computer and use it in GitHub Desktop.
Nuxt 3 Plugin providing directives and helpers to convert line breaks to <br>, <p> or arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Nuxt 3 Plugin providing directives and helpers | |
to convert line breaks to <br>, <p> or arrays. | |
--------------------------------------------- | |
Usage as directives (WARNING: can lead to XSS attack!): | |
<div v-nl2br="string" /> | |
<div v-nl2p="string" /> | |
Usage as helper in script setup: | |
const { $nl2array, $nl2br, $nl2p } = useNuxtApp() | |
const array = $nl2array(string) | |
Usage as helper in template: | |
<p v-for="(p,key) in $nl2array(string)" :key="key">{{ p }}</p> | |
*/ | |
export default defineNuxtPlugin((nuxtApp) => { | |
const nl2array = (string: string): Array<string> => { | |
return string.split(/\r?\n/) | |
} | |
const nl2br = (string: string) => { | |
return nl2array(string).join('<br />') | |
} | |
const nl2p = (string: string) => { | |
return '<p>' + nl2array(string).join('</p><p>') + '</p>' | |
} | |
nuxtApp.vueApp.directive('nl2br', (el, binding) => { | |
el.innerHTML = nl2br(binding.value) | |
}) | |
nuxtApp.vueApp.directive('nl2p', (el, binding) => { | |
el.innerHTML = nl2p(binding.value) | |
}) | |
return { | |
provide: { | |
nl2array, | |
nl2br, | |
nl2p, | |
}, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment