Using Vue, I want to show a confirmation modal that says something like "Are you sure you want to delete '{{itemName}}'?".
That's easy enough with a Javascript string being bound to a variable which is embedded in the template.
However, if I want to put the itemName
in italics to emphasis it, the only way I can find is to use v-html
, which of course would open it up to XSS.
Is there any way to style part of the string?
A confirmation dialogue is a UI pattern where the user will be given a choice to continue with their action or to cancel it. It is commonly used with destructive or irreversible actions, to make sure that the user would indeed want to proceed. In this article,we'll be implementing a reusable and modular confirmation dialogue in Vue.js.
We can check HTML attributes against the data () object values. emailEnabled is set to false, therefore, the email field is disabled. We can enable/disable other HTML attributes the same way, e.g. required.
⚠️ Vue Native has been deprecated and is no longer maintained. To let users interact with your app, we can use the v-bind directive to attach event listeners that invoke methods on our Vue Native instances:
You can try to use a package like sanitize-html. Here is how I would do it:
Install:
npm install sanitize-html
main.js:
import sanitizeHTML from 'sanitize-html';
Vue.prototype.$sanitize = sanitizeHTML;
YourComponent.vue:
<div v-html="$sanitize(itemName)" />
Have a look at the README for more information about default options for allowed tags and attributes.
EDIT resp. Alternatives:
sanitize-html
has a drawback of a 327 KB weight. But there are smaller packages available:
EDIT 2:
There is a package vue-dompuritfy-html which we are using in our projects now. After installing you can simply use
<div v-dompurify-html="itemName" />
Bonus: with the use of this package you cover the recommended eslint rule vue/no-v-html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With