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

Vue 2 component styles without Vue loader

考虑到只有一个文件组件(如shown in the guide),

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

<template>
  <div class="example">hi</div>
</template>

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

考虑到样式是有范围的,

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

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

可以手动设置示波器,vue-loader自动设置。

这是文档的示例。添加某种 ID,在本例中为“_v-f3f3eg9”,以仅针对该元素确定 class 的范围。

<style>
.example[_v-f3f3eg9] {
  color: red;
}
</style>

Vue.component('my-component', {
    template: '<div class="example" _v-f3f3eg9>hi</div>'
});

我一直使用 Rollup (+ Bublé) + Vue.js。非常简单快速。

汇总配置如下:

import vue from 'rollup-plugin-vue';
import resolve from 'rollup-plugin-node-resolve';
import buble from 'rollup-plugin-buble';

const pkg = require('./package.json');
const external = Object.keys(pkg.dependencies);

export default {
  external,
  globals: { vue: 'Vue' },
  entry: 'src/entry.js',
  plugins: [
    resolve(),
    vue({ compileTemplate: true, css: true }),
    buble({ target: { ie: 9 }})
  ],
  targets: [
    { dest: 'dist/vue-rollup-example.cjs.js', format: 'cjs' },
    { dest: 'dist/vue-rollup-example.umd.js', format: 'umd' }
  ]
};

我做了一个boilerplate repo:

git clone https://github.com/jonataswalker/vue-rollup-example.git
cd vue-rollup-example
npm install
npm run build

而不是在 Vue 组件中使用 template 实例,您可以利用 'closer-to-the-compiler alternative' 和 render 函数,而不需要 Vue Loader或编译器。您可以使用 createElement 函数中的第二个参数添加任何其他属性,这会给您带来很大的灵活性,而不仅仅是样式。

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

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

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

注意: 这里需要注意的是,该样式只会应用于声明它的组件,因此它可能无法在同一 class 就像 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'
});