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} pxcorrectly combines thestrokeWidthvariable with thepxunit, producing a string like"3 px"which is a valid value for the SVGstroke-widthattribute. - SVG attributes like
stroke-widthaccept values with explicit units (px, em, etc.) or unitless numbers (which default to px anyway). So even if you just wrote:stroke-width="strokeWidth"(assumingstrokeWidthis 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
相关产品推荐
相关产品推荐

