Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access component variable inside style in single file in Vue JS

Is there any vue plugin that can allows us to use template variable in side <style/> tag in Single File Components for e.g.

<template>

    <div>{{ display }}</div>

</template>


<script>

    export default {
        data(){
            return { display: 'block' }
        }
    }

</script>


<style>
    body {
        display: {{ display }}
    }
</style>

Any better way/plugin to do this??

I already have known about :style and :class

like image 909
Yogesh Jagdale Avatar asked Mar 09 '18 14:03

Yogesh Jagdale


People also ask

What is Vue single file component?

Vue Single-File Components (a.k.a. *.vue files, abbreviated as SFC) is a special file format that allows us to encapsulate the template, logic, and styling of a Vue component in a single file. Here's an example SFC: vue <script> export default { data() { return { greeting: 'Hello World!'

How do I get a component in Vue?

Open the file in your code editor. Create the component's template section by adding <template></template> to the top of the file. Create a <script></script> section below your template section. Inside the <script> tags, add a default exported object export default {} , which is your component object.


1 Answers

I think there is no way to access the Vue model (data layer) inside <Style> in the current version of Vue. Vue only control the DOM tree but not help you work around on CSSOM.

You are probably using WebPack or other bundler and writing modularized component in single file where you have <template>, <script>, and <style>. Your bundler will have a way to convert <template> into Vue render function, but style here is purely css and will be bundled into a single css file.

If you want to set a styling value dynamically that controlled by your component, you need to find a way to inject them in run-time, i.e. using the Vue version of styled-component (as they came from React originally). But you will lose the caching ability, unless you also save the value in localStorage.

like image 170
Leo Li Avatar answered Oct 23 '22 00:10

Leo Li