Robert Kusznier
Robert Kusznier

Reputation: 6941

Can you somehow use a value from <script> in <style> in Vue component?

Is it possible for a Vue component to use inside part of the component a JavaScript value defined in part of the component?

For example:

<script>
export default {
  props: {
    value: Boolean
  }
};
</script>

<style lang="scss" scoped>
@if (value) {
  // Do something
}
</style>

Upvotes: 2

Views: 3759

Answers (3)

li x
li x

Reputation: 4061

In Vue the preferred method for interacting between your data and styles is by using class bindings Here's the docs:

The main reason for using class bindings is because of Separation of Concerns both our data and style sections should only be concerened with talking to the template and introducing ways in which we can share data between the two would allow you to make further mistakes. It's also not a very efficent way to managing styles which are only concerned with the template data, so why create crossover?

example:

Template

<div class="static"
     v-bind:class="{ active: value }">
</div>

data

export default {
  props: {
    value: Boolean
  }
};

style

<style lang="scss" scoped>
  .active{
     color: green;
  }
</style>

As you can see here both of our separate components are directly relying on only the template to apply our custom styling.

Upvotes: 2

bbsimonbb
bbsimonbb

Reputation: 29022

No. Vue single file components and SASS preprocessing do not change the fundamental given: css are static. Your script will run in the browser, after your SASS has been resolved during the build step.

Most of the time, you get the dynamism you need by manipulating the classes on an element with vue, but there are some occasions where you want to directly manage the styles. For example, you might want to manage the position of an object with Vue. In this case, use a dynamic style binding ( which works and looks just like a dynamic class binding). These styles are injected directly onto the element, so they have precedence over all styles defined via css.

<div :style='myDynamicStyle'>...</div>

computed:{
    myDynamicStyle(){
        return {
            // define your style, in javascript, in camelCase
            position:absolute,
            top: this.myReactiveVar
            // when myReactiveVar changes, your thang will move baby
            ...

Upvotes: 5

Fab
Fab

Reputation: 4657

No, it's not possible, but you can achieve it almost in the same way using your property as main element's class. Like this:

<template>
  <div :class="myProp">
    <h1>Content 1</h1>
    <h2>Content 2</h2>
  </div>
</template>

<script>
  export default {
    props: {
      myProp: String
    }
  };
</script>

<style lang="scss" scoped>
  .propValue {
    & h1 {
      /* my rules here */
    }
    & h2 {
      /* my rules here */
    }
  }
</style>

Upvotes: 3

Related Questions