Skip to content

Instantly share code, notes, and snippets.

@jkga
Created June 21, 2018 15:52
Show Gist options
  • Save jkga/0ea90663aaad46030740197a73c37a9f to your computer and use it in GitHub Desktop.
Save jkga/0ea90663aaad46030740197a73c37a9f to your computer and use it in GitHub Desktop.
Adding style inside Vue components' template without using vue-loader
// app-style.js
// adding <style></style> directly inside template will result in error or empty element which
// this component is trying to address
// this will allow you to dynamically insert css inside Vue template without the use of vue loader
// or if you do not want to use .vue extension at all
// however it doesnt really apply scope css (for now).
export default {
name: 'app-style',
data: function(){
return {
style: ''
}
},
created: function () {
this.$slots.default.forEach((val, index) => {
this.style += val.text
})
},
mounted: function() {
// create <style/>
const styl = document.createElement('style')
const txtNode = document.createTextNode(this.style)
// replace current node
styl.append(txtNode)
this.$el.replaceWith(styl)
},
template:'<span><!-- please see styling in head section--></span>'
}
/**------------------------------------------------------------------------------------------------------
| another Vue component
--------------------------------------------------------------------------------------------------------*/
import appStyle from './app-style'
import style from './your-style-file'
export default {
data: { },
components: {
'app-style': appStyle, // app-style component
},
template: `
<app-style>${style.toString()}</app-style>
<another-custom-component></another-custom-component>
<app-sidebar></app-sidebar>
`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment