Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: How can I make dynamically created HTML use scoped CSS?

Short version:

I'm generating a string with HTML in a component's method, and I can't figure out how to style that HTML with scoped CSS, because it's missing the data attribute for scoping.

Slightly longer version:

I have a function called highlight which takes a string and returns an HTML string with all occurrences of a search term highlighted, meaning surrounded by a <span class="match">. However, since I'm doing this manually in a string, that span doesn't get the special data attribute that the scoped CSS in my Vue component needs to work, so the only way for me to style those matches is to make my CSS not scoped, which I'd like to not have to do. Is there a more Vue-specific way for me to do this? The function looks like this:

// Source: http://stackoverflow.com/a/280805/2874789
function highlight(data, search) {
    return data.replace(
      new RegExp("(" + preg_quote(search) + ")", 'gi'),
      "<span class=match>$1</span>"
    );
}

(preg_quote is just a function that escapes things that need to be escaped)

Thanks!

like image 434
Christopher Shroba Avatar asked Mar 27 '17 17:03

Christopher Shroba


1 Answers

Just ran into something similar. The easiest way around it, don't scope it. Just namespace your markup and CSS classes so they don't get inherited from some other module and you're done. Messing around with JavaScript to pull this off is overkill.

like image 74
Matt Kaye Avatar answered Sep 24 '22 16:09

Matt Kaye