typescript - Vue + TypeScript + CSS 模块

标签 typescript vue.js css-modules

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

最佳答案

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

关于typescript - Vue + TypeScript + CSS 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997704/

相关文章:

Angular 服务 - 返回的对象类型是对象,而不是指定的泛型类型

css - Angular 2 @Component 样式

vue.js - 如何在 vue js web 组件中正确使用插槽并应用样式

css - 使用 css 模块如何定义全局类

arrays - 如何在嵌套的 FormArrays 中添加元素?

node.js - 使用 TypeScript 从 Sequelize 的响应中获取属性

vue-component - 使用相同的形式进行创建和读取操作

javascript - 如何在 BootstrapVue 元素上使用 Vue Test Utils 触发事件?

css - 使用 CSS 模块防止大量与样式相关的 React Prop

reactjs - 我可以在 create-react-app v2 中使用 css 模块覆盖 Material-UI 吗?