没有 Vue 加载器的 Vue 2 组件样式 [英] Vue 2 component styles without Vue loader

查看:16
本文介绍了没有 Vue 加载器的 Vue 2 组件样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Considering that there is single file component (as shown in the guide),

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

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

在非模块化 ES5/ES6 环境中,没有 Vue loader 怎么做同样的事情?

How can the same thing be done without Vue loader in non-modular ES5/ES6 environment?

考虑到样式是有作用域的,

Considering that the style is scoped,

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

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

Is there a way to implement scoped CSS in non-modular environment, too? If there's none, is there a way to implement it in modular environment (Webpack), but without Vue loader and custom .vue format?

推荐答案

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

Instead of using the template instance in the Vue component, you can harness a 'closer-to-the-compiler alternative' with the render function without the need for the Vue Loader or compiler. You can add any additional attributes with the second parameter in the createElement function and this will give you a lot of flexibility on top of just styles.

请参阅指南中的渲染函数部分了解更多信息以及数据 obj 中允许的完整选项:

See the Render Functions section in the guide for more info and the full options allowed in the data obj:

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

https://vuejs.org/v2/指南/渲染功能#The-Data-Object-In-Depth

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

Note: The caveat here is that the style will only apply to the component it is declared in, so it might not be able to used across multiple components of the same class like CSS would be. Not sure if thats also what you want to achieve.

文档中的一个例子迎合了这个用例:

An example from the docs catered to this use case:

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'
});

这篇关于没有 Vue 加载器的 Vue 2 组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆