Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Vue 2 component styles without Vue loader

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

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

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

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>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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#The-Data-Object-In-Depth

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...