gpt4 book ai didi

vue.js - 可重用的组件以在Vue.js中呈现按钮或路由器链接

转载 作者:行者123 更新时间:2023-12-03 06:43:00 25 4
gpt4 key购买 nike

我是使用Vue.js的新手,并且在创建Button组件时遇到了困难。

如何将该组件编程为条件渲染?换句话说,也许应该呈现为router-link还是button?像那样:

<Button type="button" @click="alert('hi!')">It's a button.</Button>
// -> Should return as a <button>.

<Button :to="{ name: 'SomeRoute' }">It's a link.</Button>
// -> Should return as a <router-link>.

最佳答案

您可以在render()内切换标签,也可以只使用<component>

根据official specification for Dynamic Components:

You can use the same mount point and dynamically switch between multiple components using the reserved <component> element and dynamically bind to it's is attribute.



这是您的情况的示例:

ButtonControl.vue

<template>
<component :is="type" :to="to">
{{ value }}
</component>
</template>

<script>
export default {
computed: {
type () {
if (this.to) {
return 'router-link'
}

return 'button'
}
},

props: {
to: {
required: false
},
value: {
type: String
}
}
}
</script>

现在,您可以轻松地将它用于 button:

<button-control value="Something"></button-control>

router-link:

<button-control to="/" value="Something"></button-control>

当有必要创建可能具有链接或不具有链接的元素(例如按钮或卡片)时,请记住这是一种出色的行为。

关于vue.js - 可重用的组件以在Vue.js中呈现按钮或路由器链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com