【问题标题】:Vue + TypeScript + CSS moduleVue + TypeScript + CSS 模块
【发布时间】:2019-05-28 14:11:38
【问题描述】:

我有 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 属性。如何解决?

【问题讨论】:

    标签: typescript vue.js css-modules


    【解决方案1】:

    您需要增加 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 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-27
      • 2019-03-05
      • 2021-12-09
      • 2019-10-01
      • 2021-01-12
      • 2021-12-07
      • 2022-10-16
      • 2019-07-21
      相关资源
      最近更新 更多