最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access component variable inside style in single file in Vue JS - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Mar 9, 2018 at 15:37 Yogesh Jagdale asked Mar 9, 2018 at 14:11 Yogesh JagdaleYogesh Jagdale 7309 silver badges23 bronze badges 7
  • You would do this using CSS classes designed for this purpose, not by directly manipulating CSS rules. – connexo Commented Mar 9, 2018 at 14:17
  • Yes I got you! but when we want @media css manipulation then its bee issue! – Yogesh Jagdale Commented Mar 9, 2018 at 14:19
  • I don't see how that use case would require any different approach. – connexo Commented Mar 9, 2018 at 14:20
  • @connexo think like you want different image on desktop and different image on mobile! – Yogesh Jagdale Commented Mar 9, 2018 at 14:24
  • You'd do that with CSS... No Javascript involved at all. – connexo Commented Mar 9, 2018 at 14:28
 |  Show 2 more ments

2 Answers 2

Reset to default 3

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 ponent 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 ponent, you need to find a way to inject them in run-time, i.e. using the Vue version of styled-ponent (as they came from React originally). But you will lose the caching ability, unless you also save the value in localStorage.

https://v2.vuejs/v2/guide/class-and-style.html#Object-Syntax-1

You can put whatever you want in your style attribute by binding inline styles:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
发布评论

评论列表(0)

  1. 暂无评论