Composition-api: Cannot work with CSS Modules

Created on 3 Jul 2019  路  3Comments  路  Source: vuejs/composition-api

<script>
  export default {
    props: {
      themeName: String
    },

    computed: {
      $theme () {
        return this[this.themeName]
      }
    }
  }
</script>

<style module="$a">
  .wrapper {
    background: #000;
  }
</style>

<style module="$b">
  .wrapper {
    background: #fff;
  }
</style>

setup (props, context) cannot work with CSS Modules, because context does not has property $a or $b.

ecosystem

Most helpful comment

My workaround

import { getCurrentInstance } from '@vue/composition-api';

export default {
  setup () {
     const { $style } = getCurrentInstance()!
  }
}

All 3 comments

Also, when using without custom inject names, context does not have the property $style:

<script>
  export default {
    setup(props, context) {
      // Get undefined instead of { wrapper: <random-string> }
      return context.$style;
    }
  }
</script>

<style module>
  .wrapper {
    background: #000;
  }
</style>

As a workaround, depending on your usage, it is possible to extract $a $b and $style from the onBeforeMount hook. For example:

<script>
  import { onBeforeMount } from '@vue/composition-api';
  export default {
    setup() {
      const css = { $a, $b, $style };
      onBeforeMount(function(){
        ({ $a: css.$a, $b: css.$b, $style: css.$style } = this);
      });
      // css.$a, css.$b, css.$style are now available for use in computed properties, etc.
      return {
        // no need to return $a/$b/$styles, added to instance by vue-loader
      };
    }
  }
</script>

<style module>
  .wrapper {
    background: #000;
  }
</style>

<style module="$a">
  .wrapper {
    background: #ccc;
  }
</style>

<style module="$b">
  .wrapper {
    background: #fff;
  }
</style>

My workaround

import { getCurrentInstance } from '@vue/composition-api';

export default {
  setup () {
     const { $style } = getCurrentInstance()!
  }
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sapphi-red picture sapphi-red  路  4Comments

tomlla picture tomlla  路  6Comments

carlmjohnson picture carlmjohnson  路  5Comments

kwanjas3 picture kwanjas3  路  4Comments

ycmjason picture ycmjason  路  5Comments