Модуль Vue + TypeScript + CSS - PullRequest
       12

Модуль Vue + TypeScript + CSS

0 голосов
/ 01 января 2019

У меня есть SFC (одиночный компонент vue), который использует TypeScript, функцию рендеринга и модуль CSS

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  props: {
    mode: {
      type: String,
      default: 'td', // or th
    },
  },
  render(h) {
    return h('tr', [
      'preview',
      'name',
      'price',
      'count',
      'delete',
    ].map(col => h(this.mode, { class: this.$style[col] },
      this.$slots[col])));
  },
});
</script>

<style lang="stylus" module>
.preview
  display none

.delete
  text-align center

@media (min-width 768px)
  .preview
    display table-row
</style>

И я получаю ошибку от TypeScript:

ERROR in /home/oks/apps/shop/src/components/CartRow.vue
18:45 Property '$style' does not exist on type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<{ mode: string; }>>
'.
    16 |       'count',
    17 |       'delete',
  > 18 |     ].map(col => h(this.mode, { class: this.$style[col] }, this.$slots[col])));
       |                                             ^
    19 |   },
    20 | });

В JSэтот код работает, но TS не знает о модулях CSS и свойстве this.$style.Как это исправить?

1 Ответ

0 голосов
/ 02 января 2019

Вам нужно увеличить набор Vue.Создайте файл объявления (например, sfc.d.ts) и добавьте следующее:

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
  // 3. Declare augmentation for Vue
  interface Vue {
   $style: any
  }
}

Измените any, чтобы оно соответствовало объявлению типа $style, например:

$style: { [key: string]: string }
...