nuxt3中使用NuxtColorMode,component加载不出来

文章讲述了在将NuxtColorMode官方Demo迁移到nuxt3项目时遇到的问题,涉及到内置组件的resolveComponent使用。解决方法是确保在is属性中正确地解析并使用resolveComponent。
摘要由CSDN通过智能技术生成

问题描述

这是NuxtColorMode官方的demo:Demo
你也可以直接打开这个链接在线看该Demo的效果Online examples
但是当你把这个Demo迁移到你的项目中,会发现某些组件加载不出来。

原因分析:

在nuxt3中使用内置的component 组件中的is是需要先resolve的: resolveComponent

<template>
 	<component :is="clickable ? MyButton : 'div'" />
</template>

<script setup>
	const MyButton = resolveComponent('MyButton')  // 需要使用resolveComponent辅助方法解析组件
</script>

而官方的组件并没有这么做,而是使用vue原先的写法,所以迁移后是跑不起来的:
nuxt3中使用NuxtColorMode,踩坑录

解决方案:

只要resolve了再放到is中就可以

<template>
  <div>
    <ul>
      <li
        v-for="{ color, comp } of modeList"
        :key="color"
        :class="{
          preferred: !$colorMode.unknown && color === $colorMode.preference,
          selected: !$colorMode.unknown && color === $colorMode.value,
        }"
      >
        <component :is="comp" @click="$colorMode.preference = color" />
      </li>
    </ul>
    <p>
      <ColorScheme placeholder="..." tag="span">
        Color mode: <b>{{ $colorMode.preference }}</b>
        <span v-if="$colorMode.preference === 'system'"
          >&nbsp;(<i>{{ $colorMode.value }}</i> mode detected)</span
        >
      </ColorScheme>
    </p>
  </div>
</template>
<script setup>
const IconDark = resolveComponent('IconDark');
const IconLight = resolveComponent('IconLight');
const IconSepia = resolveComponent('IconSepia');
const IconSystem = resolveComponent('IconSystem');
const modeList = [
  {
    color: 'system',
    comp: IconSystem,
  },
  {
    color: 'light',
    comp: IconLight,
  },
  {
    color: 'dark',
    comp: IconDark,
  },
  {
    color: 'sepia',
    comp: IconSepia,
  },
];
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值