Vue Binding Inline Style

Keywords: Vue Attribute

Using v-bind:style, you can bind inline styles to elements in a way similar to: class, with object grammar and array grammar, which seems to write CSS directly on elements:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example</title>

</head>
<body>

    <div id="app">
        <div :style="{ 'color': color, 'fontSize': fontSize + 'px' }"></div>
    </div>

    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

    <script>

        var app = new Vue({
            el: '#app',
            data: {
                color: 'red',
                fontSize: 14
            },
        });

    </script>

</body>
</html>

CSS attribute names are named by camelCase or kebab-case, and rendered as follows:

<div style="color: red; font-size: 14px">text</div>

In most cases, writing a series of styles directly is not easy to read and maintain, so it is usually written in data or computer. Take data as an example to write the above examples:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example</title>

</head>
<body>

    <div id="app">
        <div :style="styles"></div>
    </div>

    

    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

    <script>

        var app = new Vue({
            el: '#app',
            data: {
                color: 'red',
                fontSize: 14 + 'px' 
            },

            
        });
    </script>

</body>
</html>

When applying multiple style objects, you can use array syntax:

<div :style="[styleA, styleB]">text</div>

In real business, style's array grammar is not commonly used, because it can be written in an object; the more common application is to compute attributes.
In addition, when using: style, Vue.js automatically prefixes special CSS attribute names, such as transform.

Posted by able on Thu, 31 Jan 2019 22:30:15 -0800