Case scenario:

Recently our app needs to follow the system to switch the theme plan, need to schedule (jiaban) to achieve

Implementation analysis:

1, CSS variable var to achieve theme switching

2. Interact with the app to get the current theme

According to the rules first: give chestnuts

When using:

The first argument to the method is the name of the custom property to replace. The optional second argument to the function is used as a fallback value. If the custom property referenced by the first argument is invalid, the function uses the second value.

/* Define a value in the parent element style */.component {--text-color: #080; /* header-color is not set */} /* Use it in the component style: */.component.text {color: var(--text-color, black); /* --text-color */}.component. header {color: var(--header-color, blue); /* Here the color is rebooted to blue */}Copy the code

If the first value is in fact did not detect the definition with the second value, similar to let a = b | | 1

I did a quick demo just for your reference.

The effect is as follows:

The root definition can be placed in base.less. The demo indicates the reference implementation

Remark: Attach code

<template> <div class="loginPage"> <p class=" text-align "style =" box-sizing: border-box; color: #999999" Type ="primary" @click="changeTheme('white')"> </van-button> </div></ div></template><script setup>  => { document.documentElement.dataset.theme = theme}</script><style lang="less" scoped>.loginPage { padding-top: 10px; .btns { display: flex; justify-content: space-between; padding: 10px 20px; box-sizing: border-box; }}</style><style lang="less">:root { --primary: #ffffff; --text-color: #343a40; --border-color: #343a40; }:root[data-theme='white'] { --primary: #ffffff; --text-color: #343a40; --border-color: #343a40; }:root[data-theme='black'] { --primary: #343a40; --text-color: #f8f9fa; --border-color: #e9ecef; }html,body { background-color: var(--primary); height: 100%; width: 100%; overscroll-behavior-y: none; }.text { font-size: 20px; margin: 0 20px; padding: 10px; border-radius: 4px; color: var(--text-color); border: 2px solid var(--border-color); }</style>Copy the code