繁体   English   中英

Vue / Typescript:如何键入返回css的对象文字?

[英]Vue/Typescript: how to type an object literal that returns css?

我在这里关注答案( Vue is it possible to use a prop for style? (SCSS/SASS) )关于如何在我的 css 中使用道具。 我想将initWidth作为道具传递,但它的默认设置为300 然后我将初始数据设置为等于该道具,以便计算属性可以访问它。 我收到一个打字稿错误,尽管Property 'baseWidth' does not exist on type '{ cssProps(): void; }'. 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",
       }
    }
}

对 Options API 的 TypeScript 支持有一个已知限制,需要在computed上注释返回类型

由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。 出于这个原因,您可能需要在rendercomputed中的方法上注释返回类型。

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

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

import Vue from 'vue'

export default Vue.extend({
  computed: {           👇
    cssProps(): Record<string, string> {
      return { /*...*/ }
    }
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM