首页 > 解决方案 > Pass Vuejs Data in Style (SFA)

问题描述

I have a beginner question. For example i have a componnent that have a Boolean prop. Deppending on the values of the prop i'm setting the path to which Less he should to take, but that doesn't work. Does anyone know how to do that? And if that is possible?

<template>
  <div class="my-style">Text</div>
</template>

<script>
  export default {
    props: {
      isFirstApp: Boolean,
    },
    data: function() {
       return {
         isFirst: true,
         path: '',
      }
    }
    created: function () {
        if(this.isFirstApp){
          this.path = '/styles/vars1.less';
        }else{
          this.path = '/oldstyles/vars2.less';
        }
    },
 }
</script>

<style lang="less" scoped>
  @import `${path}`;

  .my-style {
    color: @my-variable;
  }
</style>

标签: vue.jsvuejs2vue-component

解决方案


It's a bit of a hack, but you can achieve this by creating scss-style variables in the element's style and then using these in the actual style to set 'real' css properties. It works as the variables set in style are ignored by the browser as they are not valid css properties, but scss gets access to all previously set properties, and these appear as variables.

Code Sandbox

<template>
  <div class="hello">
    <!-- Set the style to include the values from cssVars computed property -->
    <p :style="cssVars">Hello World</p>
    <!-- type in a new color name/#rgb value to dynamically change it -->
    <input v-model="color">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      color: "red"
    };
  },
  computed: {
    // Return an object containing scss variables
    cssVars() {
      return {
        "--color": this.color
      };
    }
  }
};
</script>

<style scoped>
// Use the variables defined in style to set 'real' css properties
p {
  color: var(--color);
}
</style>

推荐阅读