Pass object data to styles in Vue.js

2019-02-25 14:04发布

I want to be able to pass data from a object to the <styles> in a single file component. However, it doesn't seem like this is possible.

What I'm trying to achieve:

<template></template>

<script>
export default {
    data: function() {
        return { color: "#f00" }
    }
}
</script>

<style>
body {
    background-color: this.color
}
</style>

标签: vue.js
1条回答
甜甜的少女心
2楼-- · 2019-02-25 14:15

As far as I'm aware, you are not able to pass data from the component to its stylesheets.

The best practice as far as dynamic styling is to use v-bind:class or v-bind:style if needed. The <style> section should be used for the CSS templating language only.

<template>
    <p :style="{ backgroundColor: bgColor }">Lorem ipsum</p>
</template>

<script>
    export default {
        data() {
            return {
                bgColor: '#000'
            }
        }
    }
</script>

Let me know if you have any other questions!

Update

Since the goal is to use it for Sass functions like darken, I would recommend managing the various colors needed through utility classes instead.

查看更多
登录 后发表回答