How to limit the scope of a Vue.js component's style? -


i experimenting single file .vue components , first successful build surprised me scope of component style. speaking, under impression single file components self-contained, including scope of components.

the component .vue file is

<template>     <div>         hello {{who}}     </div> </template>  <script> module.exports =  {     data: function () {         return {             who: "john"         }     } } </script>  <style> div {     color: white;     background-color: blue; } </style> 

it built via webpackthough following webpack.config.js

module.exports = {     entry: './entry.js',     output: {         filename: 'bundle.js'     },     devserver: {         inline: true     },     module: {         rules: [{             test: /\.vue$/,             loader: 'vue-loader'         }]     } } 

and entry.js

import vue 'vue/dist/vue.js' import componentone './component1.vue'  //vue.component('component-one', componentone) new vue({     el: "#time",     data: {         greetings: "bonjour"     },     components: { componentone } }) 

the html file binding is

<!doctype html> <html lang="en">     <body>         greetings:         <div id="time">             {{greetings}}             <component-one></component-one>         </div>           <script src='bundle.js'></script>     </body> </html> 

the rendered result is

enter image description here

the style definitions component-one div applied parent div (with id=time). expected behaviour? shouldn't styling confined component?


note: can assign id div in component's template , therefore contain styling - question why behaviour expected in context of components self-containement.

the scope of styling will not limited scope of component, unless explicitly mark style scoped attribute:

<style scoped> div {     color: white;     background-color: blue; } </style> 

furthermore, since using webpack create single bundled file, there no way browser separate styles 1 component next, since loaded , parsed @ same time.

if wanted lessen footprint of component on other components, you'd need both scope styles , utilize code splitting, although in case, marking style sufficient.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -