Vue3+ts如何向html元素中添加属性,或者扩展已有的属性?


​​

img

使用view标签时,不允许被绑定数组,只能用这两个属性。

img

请问我该如何做,才能将想要的类型声明,扩展给这个"SVGAttributes"呢?

img

我尝试效仿查阅来的react进行声明,但是并没有效果,求告知,感谢!

 

 

 

 

Vue3中,你可以通过声明自定义元素并扩展已有的属性来实现这一点。
例如,如果你要扩展SVG元素,可以:
1. 声明 SVG 元素:
ts
declare global {
  namespace JSX {
    interface IntrinsicElements {
      svg: SVGElement
    }
  }
}
2. 扩展 SVGAttributes 来添加你想要的属性:
ts 
interface SVGAttributes extends DOMAttributes<SVGElement> {
  'other-attr'?: string
}
3. 然后你就可以在 SVG 元素中使用 other-attr 属性了:
tsx
<svg other-attr="some value" />
具体代码示例:
ts
// 声明 SVG 元素
declare global {
  namespace JSX {
    interface IntrinsicElements {
      svg: SVGElement
    }
  }
}

// 扩展 SVGAttributes
interface SVGAttributes extends DOMAttributes<SVGElement> {
  'other-attr'?: string
}

// 使用扩展的属性
<svg other-attr="some value" /> 
所以在你的例子中,你可以:
1. 声明svg元素
2. 扩展SVGAttributes并添加你想要的属性(比如extraAttr)
3. 在svg元素中使用extraAttr属性
希望这能帮助你!
Claude 非常感谢您的详细解释,我已经理解了,只是还有以下疑问:
1. declare global namespace JSX 这一块,声明的意思是,在JSX语法中,允许使用<svg>这样的写法?
2. DOMAttributes到底是什么?我在网上搜不到它的定义。它代表所有DOM元素的属性集合吗?
3. 除了扩展SVGAttributes以外,如果我想新增一个全新的元素,比如<my-element>,应该如何定义和使用它?