tusen-ai / naive-ui

A Vue 3 Component Library. Fairly Complete. Theme Customizable. Uses TypeScript. Fast.
https://www.naiveui.com
MIT License
16.18k stars 1.67k forks source link

n-switch的插槽checked-icon在首次渲染时,没有成功触发。 #5046

Closed Numb9870 closed 1 year ago

Numb9870 commented 1 year ago

TuSimple/naive-ui version (版本)

2.34.4

Vue version (Vue 版本)

3.3.4

Browser and its version (浏览器及其版本)

Edge版本 114.0.1823.67 (正式版本) (64 位)

System and its version (系统及其版本)

window11

Node version (Node 版本)

v16.18.0

Reappearance link (重现链接)

https://github.com/Numb9870/WebGame

Reappearance steps (重现步骤)

// template部分

<n-switch v-model:value="theme" size="large" @update:value="handleThemeChange">
    <template #checked-icon>
        <n-icon :component="MoonStars" />
    </template>
    <template #unchecked-icon>
        <n-icon :component="Sun" />
    </template>
</n-switch>

// script部分

onBeforeMount(() => {
    // SystemConfigStore为本地localStorage去更改主题
    if (SystemConfigStore.theme !== null) {
        theme.value = true
    } else {
        theme.value = false
    }
})

Expected results (期望的结果)

当SystemConfigStore.theme !== null时,此时localStorage中的theme储存着darkTheme:GlobalTheme,打开switch开关,显示插槽<template #checked-icon>....

ps:这是手动开关,显示了插槽的icon 9f784c557446a957.png

Actual results (实际的结果)

页面刷新时,switch开关已打开,但未显示插槽内的icon

72aea582ef564a6a.png

Remarks (补充说明)

XieZongChen commented 1 year ago

简单看了一下,主要问题是 n-switch 所使用的 --n-icon-color 在 theme 设置为 dark 且刷新页面的情况下取到的是 light 的颜色,而源码里本意是想取到 dark 的颜色。 看了你提供的复现,发现 theme 的状态有用到 pinia,所以我怀疑是初始化过程中 theme 的初始化的时机问题(出现问题后只要切换一次 light 就会复原)。 由于问题比较复杂(牵扯的库比较多),所以排查修复时间比较长,如果你不想等待,可以自己将传给 n-switchn-icon 的颜色写死,可以用 class 或 style 覆盖的方式进行。

Sepush commented 1 year ago

when you store the theme var to pinia lose the proerty of self a function darkTheme and lightTheme naive export image your pinia store image so you get the wrong css var color which introduce it solution do not store the theme just get from naive instead store 'dark' or 'light' vueuse useDark impl it https://vueuse.org/core/useDark/

Numb9870 commented 1 year ago

So,We should not store the darkTheme provided by Naive. To determine the brightness label you set and import it from Naive again. This bug has been resolved


import { darkTheme } from 'naive-ui'
onBeforeMount(() => {
    // SystemConfigStore为本地localStorage去更改主题
    // 修改主题
    SystemConfigStore.theme ? theme.value = darkTheme : theme.value = null
})