我在我的 vue ts 项目中使用这种方法来设置样式。
private styleTableObject: CSSStyleSheet = {
width: '100%',
height: '76%'
}
Run Code Online (Sandbox Code Playgroud)
我是被迫的类型any
。
private styleTableObject: any = {
width: '100%',
height: '76%'
}
Run Code Online (Sandbox Code Playgroud)
错误日志:
Type '{ width: string; height: string; }' is not assignable to type 'CSSStyleSheet'.
Object literal may only specify known properties, and 'width' does not exist in type 'CSSStyleSheet'.
Run Code Online (Sandbox Code Playgroud)
如果使用可视代码助手中的任何类型,我会收到错误日志:
Type '{ width: string; height: string; }' is not assignable to type 'StyleSheet'.
Object literal may only specify known properties, and 'width' does not exist in type 'StyleSheet'.
219:13 Type '{ width: string; height: string; }' is missing the following properties from type 'CSSStyleDeclaration': alignContent, alignItems, alignSelf, alignmentBaseline, and 382 more.
Run Code Online (Sandbox Code Playgroud)
Owl*_*Owl 11
改用Partial<CSSStyleDeclaration>
部分<T>
构造一个类型,并将 T 的所有属性设置为可选。该实用程序将返回一个表示给定类型的所有子集的类型
来自: https: //www.typescriptlang.org/docs/handbook/utility-types.html#partialt
所以你的代码看起来像这样
private styleTableObject: Partial<CSSStyleDeclaration> = {
width: '100%',
height: '76%'
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Vue 3 为 CSS 属性对象提供了自己的类型。注意Partial<CSSStyleDeclaration>
会导致模板中出现类型检查错误(即启用 Volar 时):
import type { CSSProperties } from 'vue'
const styleTableObject: CSSProperties = {
width: '100%',
height: '76%'
}
<div :style="styleTableObject" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3932 次 |
最近记录: |