You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中此SVG/HTML属性插值方式是否正确?官方文档未说明

Is Your SVG Stroke-Width Binding in Vue Correct?

Hey there! Great question, and I can confirm that your approach <svg :stroke-width="${strokeWidth} px"> is totally valid and works as intended—here's why:

  • First, Vue's dynamic attribute binding (the colon : prefix) evaluates the JavaScript expression on the right and sets the result as the attribute's value. Your template string ${strokeWidth} px correctly combines the strokeWidth variable with the px unit, producing a string like "3 px" which is a valid value for the SVG stroke-width attribute.
  • SVG attributes like stroke-width accept values with explicit units (px, em, etc.) or unitless numbers (which default to px anyway). So even if you just wrote :stroke-width="strokeWidth" (assuming strokeWidth is a number), that would also work—but your explicit unit version is perfectly fine if you want to be clear.

While the Vue docs might not call out this exact SVG use case, this is just standard behavior for dynamic attribute bindings. Any valid JavaScript expression that returns a string (or a value Vue can coerce to a string) will work here.

As a side note, you could also write this using string concatenation instead of template literals if you prefer:

<svg :stroke-width="strokeWidth + ' px'">

Both approaches are equivalent and equally valid.

内容的提问来源于stack exchange,提问作者Aerodynamic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:52:41