如何限制Vue.js组件样式的范围?

时间:2017-07-25 14:29:26

标签: vue.js vue-component

我正在试验单个文件.vue组件,我的第一个成功构建让我对组件样式的范围感到惊讶。一般来说,我的印象是单个文件组件是自包含的,包括其组件的范围。

组件.vue文件是

<template>
    <div>
        Hello {{who}}
    </div>
</template>

<script>
module.exports =  {
    data: function () {
        return {
            who: "John"
        }
    }
}
</script>

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

通过以下webpack

通过webpack.config.js构建
module.exports = {
    entry: './entry.js',
    output: {
        filename: 'bundle.js'
    },
    devServer: {
        inline: true
    },
    module: {
        rules: [{
            test: /\.vue$/,
            loader: 'vue-loader'
        }]
    }
}

entry.js

import Vue from 'vue/dist/vue.js'
import ComponentOne from './component1.vue'

//Vue.component('component-one', ComponentOne)
new Vue({
    el: "#time",
    data: {
        greetings: "bonjour"
    },
    components: { ComponentOne }
})

将所有HTML文件绑定在一起

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

渲染结果为

enter image description here

component-one div的样式定义也适用于父divid=time)。这是预期的行为吗?造型是否不应局限于组件?

注意:我可以为我的组件id中的div分配template,因此会包含样式 - 我的问题是关于为什么会出现此行为的原因组件自我容纳的背景。

1 个答案:

答案 0 :(得分:2)

样式will not be limited的范围到组件的范围,除非您使用scoped属性明确标记样式:

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

此外,由于您使用webpack创建单个捆绑文件,因此浏览器无法将样式从一个组件分离到下一个组件,因为所有组件都将同时加载和解析。

如果你想减少组件在其他组件上的占用空间,你需要同时调整样式并使用代码分割,尽管在你的情况下,只需标记样式就足够了。