Home > Software engineering >  How to add <style> tag in Vue.js component
How to add <style> tag in Vue.js component

Time:09-27

I'm on Vue.js v2. I have a CSS stylesheet stored as a string in a variable.

import sitePackCss from '!!raw-loader!sass-loader!../../app/javascript/styles/site.sass';

I need to create a tag from my component.

<style v-html="sitePackCss" />

OR

<style>{sitePackCss}</style>

When I do either of these, I get the following error in the console:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <style>, as they will not be parsed.

How do I get this tag onto the page?

NOTE: I know this is a hacky, non-preferred way to include styles. This solution will only get used in the context of storybook, where I need to include specific CSS files for specific stories (without storybook/webpack adding them to every story). If I use normal webpack loaders, each tag is added to every story. Importing the styles as a string is the only way I've found to sidestep that behavior.

CodePudding user response:

Try to add the style to the src tag of the style in your SFC :

<style lang="sass" src="../../app/javascript/styles/site.sass">

</style>

CodePudding user response:

This seems to work!

import sitePackCss from '!!raw-loader!sass-loader!../../app/javascript/styles/site.sass';

In template:

<component is="style" type="text/css">${sitePackCss}</component>

Note: the sass files have references to fonts that were not working correctly using this technique. I had to update the staticDirs config to make those paths work. https://storybook.js.org/docs/react/configure/images-and-assets

  • Related