vue中,href,当某个变量为true, 再绑定或设置url, 如何写?
在 Vue.js 中,你可以使用绑定表达式和三元运算符来实现这个功能。例如,假如你有一个变量 showLink
,当它为 true
时,你想设置 href
属性为某个 URL(例如 "https://example.com"
),否则不设置,你可以这样写:
<a :href="showLink ? 'https://example.com' : null">My Link</a>
在这个例子中,:href
是一个绑定表达式,其值会根据 showLink
的值动态改变。如果 showLink
为 true
,href
就会被设置为 'https://example.com'
;如果 showLink
为 false
或者 null
,href
则不会被设置。
需要注意的是,如果 showLink
为 false
或 null
,生成的 <a>
标签依然会包含 href
属性,但其值会被设置为 null
,这可能会导致链接无法正常工作。如果你不希望在 showLink
为 false
或 null
时生成 href
属性,你需要使用 v-bind
指令的对象语法:
<a v-bind="{ href: showLink ? 'https://example.com' : undefined }">My Link</a>
在这个例子中,如果 showLink
为 true
,href
会被设置为 'https://example.com'
;如果 showLink
为 false
或 null
,href
属性则不会被生成。