【发布时间】:2021-10-14 22:15:55
【问题描述】:
我在 NuxtJS 应用程序中有一个 Vue 组件,我正在使用 @nuxtjs/composition-api。
我有这个组件,它是一个<Link> 组件,我想让代码更清晰。
-
我有一个计算属性,它决定了我的
UiIcon的颜色来自iconColor, iconColorHover, IconActive。但最重要的是,如果我的根组件上有一个禁用类,我想将其设置为特定颜色。它是这样工作的,但我相信它看起来不太好。 -
我发现
undefined是唯一可以用来获取UiIcon默认道具(如果未定义)的值。像''这样的空字符串会更有意义,但它被视为有效值。我必须在我的UiIcon中做一些三元条件,我想避免这种情况。<template> <div ref="rootRef" class="row"> <UiIcon v-if="linkIcon" :type="linkIcon" :color="linkIconColor" class="icon" /> <a class="link" :href="linkHref" :target="linkTarget" :rel="linkTarget === 'blank' ? 'noopener noreferrer' : null" @mouseover="linkActive = true" @mouseout="linkActive = false" > <slot></slot> </a> </div> </template> <script lang="ts"> import { defineComponent, computed, ref, toRefs, nextTick, onBeforeMount, } from '@nuxtjs/composition-api'; import { Colors } from '~/helpers/styles'; export default defineComponent({ name: 'Link', props: { href: { type: String, default: undefined, }, target: { type: String as () => '_blank' | '_self' | '_parent' | '_top', default: '_self', }, icon: { type: String, default: undefined, }, iconColor: { type: String, default: undefined, }, iconHoverColor: { type: String, default: undefined, }, }, setup(props) { const { href, target, icon, iconColor, iconHoverColor } = toRefs(props); const linkActive = ref(false); const rootRef = ref<HTMLDivElement | null>(null); const writableIconColor = ref(''); const linkIconColor = computed({ get: () => { const linkDisabled = rootRef.value?.classList.contains('disabled'); if (linkDisabled) { return Colors.DARK_GREY; } if (linkActive.value && iconHoverColor.value) { return iconHoverColor.value; } return iconColor.value; }, set: (value) => { writableIconColor.value = value; }, }); onBeforeMount(() => { nextTick(() => { const linkDisabled = rootRef.value?.classList.contains('disabled'); if (linkDisabled) { linkIconColor.value = Colors.DARK_GREY; } }); }); return { rootRef, linkHref: href, linkTarget: target, linkIcon: icon, linkIconColor, linkActive, }; }, }); </script>
【问题讨论】: