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

查看:106
本文介绍了没有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加载器,如何做同样的事情?

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

考虑到样式的作用域,

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

有没有办法在非模块化环境中实现作用域CSS?如果没有,有没有办法在模块化环境(Webpack)中实现它,但没有Vue加载器和自定义.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组件中使用模板实例,而是可以利用渲染功能<更接近编译器的替代方案无需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.

请参阅指南中的渲染函数部分以获取更多信息以及数据对象中允许的完整选项:

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 / guide / render-function#-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天全站免登陆