问题描述
这是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原先的写法,所以迁移后是跑不起来的:
解决方案:
只要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'"
> (<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>