【问题标题】:Having locally scoped CSS in Vue when creating a component using Vue.extend({})使用 Vue.extend({}) 创建组件时在 Vue 中具有本地范围的 CSS
【发布时间】:2020-05-14 03:54:52
【问题描述】:

var myComponent= Vue.extend({
    template:
    `
    <div class="container">
    </div>
    `
    ,
    props: [],
    components: {}
    ,
    data() {
        return {
        }
    },

    methods: {
    }
})



我上面有一个使用 Vue.extend 创建的组件。它接收数据、方法和其他都在本地范围内的东西。我想知道我是否可以在传递给 vue.extend() 的对象中拥有本地范围内的该组件的 CSS

我没有使用 nodejs(使用 django),所以我认为我不能在 .vue 元素中使用推荐的语法(如果我弄错了,我可以使用 .vue 文件和以下语法,请告诉我):

<style scoped>
/* local styles */
</style>

【问题讨论】:

    标签: javascript css django vue.js scope


    【解决方案1】:

    您可以将其包含在您的模板字符串属性中:

    template: `
        <div class="container">
    
            ...
    
            <style scoped> 
                /*your css*/
            </style>
    
        </div>
        `
    

    此样式标签会将所有 css 附加到您的父容器元素作为根,因此它不会影响您的整个文档。

    【讨论】:

    • 顺便说一下,这不在官方文档中,如果您的类没有在生产模式下正确构建,您应该检查如何使用 this.$style 在您的组件中为您的组件分配样式代码/vue 实例
    • this inside template解决方案在使用非节点时不起作用
    猜你喜欢
    • 2022-07-16
    • 2018-02-16
    • 2021-04-12
    • 2011-05-12
    • 2014-07-23
    • 2021-02-18
    • 2016-12-04
    • 2015-08-09
    • 2023-01-19
    相关资源
    最近更新 更多