【问题标题】:Vue/Typescript: how to type an object literal that returns css?Vue / Typescript:如何键入返回css的对象文字?
【发布时间】:2021-11-21 17:07:29
【问题描述】:

我正在关注关于如何在我的 css 中使用道具的答案 (Vue is it possible to use a prop for styling? (SCSS/ SASS))。我想传入initWidth 作为道具,但它的默认设置为300。然后我将初始数据设置为等于该道具,以便计算属性可以访问它。尽管Property 'baseWidth' does not exist on type '{ cssProps(): void; }'.,但我收到了打字稿错误。我需要为此创建一个新界面吗?

props: {
   initWidth: {
       type: Number,
       default: 300,
   }
},

data() {
    return {
       baseWidth: this.initWidth
    }
},

computed: {
    cssProps() {
       return {
           '--baseWidth': this.baseWidth + "px",
       }
    }
}

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    TypeScript 对 Options API 的支持有一个 known limitation that requires annotating return types on computed:

    由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。因此,您可能需要在 render 和 computed 等方法上注释返回类型。

    由于 cssProps() 在其返回类型上没有注释,因此组件的类型推断被破坏,并且 TypeScript 无法将 this.baseWidth 识别为数据属性。

    您可以通过将cssProps() 的返回类型注释为Record<string,string> 来解决问题:

    import Vue from 'vue'
    
    export default Vue.extend({
      computed: {           ?
        cssProps(): Record<string, string> {
          return { /*...*/ }
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2021-05-28
      • 2021-11-09
      • 1970-01-01
      • 2022-11-30
      • 2017-05-08
      • 2022-01-06
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多