不要使用click
- 处理程序v-list-item
,因为这会破坏为路由生成的底层锚标记,并且具有可访问性影响。坚持v-list-item
内置用于路由的 props:
A v-list-item
链接到外部 URL 将使用href
像这样的道具:
<v-list-item href="https://google.com">Google</v-list-item>
打开新选项卡的人将使用target="_blank"
prop:
<v-list-item target="_blank" href="https://google.com">Google</v-list-item>
内部链接使用to
道具代替href
:
<v-list-item to="/dashboard">Dashboard</v-list-item>
它们可以在新选项卡中打开target="_blank"
还有:
<v-list-item target="_blank" to="/dashboard">Dashboard</v-list-item>
Solution
在您的情况下,您有一组项目需要有条件地绑定前面提到的道具。最好使用v-bind与一个物体 https://v2.vuejs.org/v2/api/#v-bind(其中对象的键值对绑定为组件属性)根据每个项目的属性计算:
-
Compute https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties一个新的链接数组(名为
computedLinks
)有一个要绑定的新道具(名为linkProps
):
export default {
computed: {
computedLinks() {
return this.links.map(link => {
const isExternalLink = url => /^((https?:)?\/\/)/.test(url)
const linkProps = {
[isExternalLink(link.route) ? 'href' : 'to']: link.route,
}
if (link.newTab) {
linkProps.target = '_blank'
}
return {
...link,
linkProps,
}
})
},
},
}
- 更新要使用的模板
computedLinks
,并绑定每个链接的linkProps
到其对应的v-list-item
:
<v-list-item v-for="link in computedLinks" :key="link.text" v-bind="link.linkProps">
???? ????
demo https://stackblitz.com/edit/vue2-vuetify-v-list-item-with-links?file=src/views/Home.vue