没有Vue加载器的Vue 2组件样式

Est*_*ask 6 javascript vue-loader vuejs2

考虑到有单个文件组件(如指南中所示),

<style>
.example {
  color: red;
}
</style>

<template>
  <div class="example">hi</div>
</template>
Run Code Online (Sandbox Code Playgroud)

在非模块化ES5/ES6环境中如何在没有Vue加载器的情况下完成同样的事情?

考虑到风格是范围的,

<style scoped>
.example {
  color: red;
}
</style>
Run Code Online (Sandbox Code Playgroud)

有没有办法在非模块化环境中实现作用域CSS?如果没有,有没有办法在模块化环境(Webpack)中实现它,但没有Vue加载器和自定义.vue格式?

Tim*_*ood 5

template您可以使用渲染函数 "更接近编译器替代" 而不需要Vue Loader或编译器,而不是在Vue组件中使用实例.您可以使用createElement函数中的第二个参数添加任何其他属性,这将为您提供在样式之上的很多灵活性.

有关详细信息以及数据obj中允许的完整选项,请参阅指南中的" 渲染函数"部分:

https://vuejs.org/v2/guide/render-function

https://vuejs.org/v2/guide/render-function#The-Data-Object-In-Depth

注意:这里需要注意的是,样式只适用于声明它的组件,因此它可能无法像CSS那样在同一个类的多个组件中使用.不确定那也是你想要实现的.

文档中的一个示例迎合了此用例:

Vue.component('example', {
    // render function as alternative to 'template'
    render: function (createElement) {
        return createElement(
            // {String | Object | Function}
            // An HTML tag name, component options, or function
            // returning one of these. Required.
            'h2',
            // {Object}
            // A data object corresponding to the attributes
            // you would use in a template. Optional.
            {
                style: {
                    color: 'red',
                    fontSize: '28px',
                },
                domProps: {
                    innerHTML: 'My Example Header'
                }
            },
            // {String | Array}
            // Children VNodes. Optional.
            []
    )}
});

var example = new Vue({
    el: '#yourExampleId'
});
Run Code Online (Sandbox Code Playgroud)