const goods = ref([])
const good = ref({})
const getGoods = async () => { let res = await fetch("https://glpla.github.io/utils/data/coffee.json") let json = await res.json() // 更新状态 goods.value = json.cont; // 显式返回结果,便于组件使用 return json.cont; };
const getGoodById = async (id) => { // 如果第一次使用仓库,则先获取商品数据 if (goods.value.length === 0) { await getGoods(); } // 注意 === 的限制;如果定义的id是普通数值0,则可能匹配失败,因为所有的参数都是字符串类型;'0' === 0,为假 let res = goods.value.find((good) => good.id == id); // 更新状态 good.value = res; // 显式返回结果,便于组件使用 return res; };
const getByQuery = async (query) => { if (!goods.value.length) { await getAll(); } let res = goods.value.filter((item) => item.title.includes(query)); return res; };
const lists = ref([])
const addToCarts = (product) => { const existingItem = lists.value.find((item) => item.productId === product.productId); if (existingItem) { existingItem.quantity += product.quantity; } else { // replace id with nanoid lists.value.push({ ...product, id: nanoid(), create_time: Date.now() }); } };
const removeFromCart = (id) =>{ lists.value = lists.value.filter(item => item.id !== id) }
const clearCarts = () => { lists.value = []; };
const sum = computed(() => { return orders.value.reduce( (total, item) => total + item.quantity * item.price * (1 - item.discount), 0 ); });
const discount = computed(() => { return orders.value.reduce( (total, item) => total + item.quantity * item.price * item.discount, 0 ); });
. 主题切换/换肤/日夜模式
. 通过为 html 指定自定义属性实现 CSS 变量的更新达到切换效果
:root { --txt-color: #303133; --bg-color: #f1f1f1; // 其它变量... } // 类形式 .dark-theme { --txt-color: #f1f1f1; --bg-color: #131313; } // 自定义属性形式 [data-theme="dark"] { --txt-color: #f1f1f1; --bg-color: #131313; }
import { defineStore } from 'pinia' import { ref, onMounted } from 'vue' export const useThemeStore = defineStore('theme', () => { const isDarkTheme = ref(false); const toggleDarkTheme = () => { isDarkTheme.value = !isDarkTheme.value; // 方案1:设置针自定义属性 document.documentElement.setAttribute('data-theme', isDarkTheme.value ? 'dark' : 'light'); // 方案2:设置类 // document.documentElement.classList.toggle("dark-theme"); }; return { isDarkTheme, toggleDarkTheme } })
import { useThemeStore } from '@/stores/theme'; const themeStore = useThemeStore();
<div class="theme-icon" @click="themeStore.toggleDarkTheme"> <span class="iconfont" :class="themeStore.isDarkTheme ? 'icon-Moon-Star' : 'icon-Sun'"></span> </div>
import { ref } from 'vue' import { defineStore } from 'pinia' export const useMenuStore = defineStore('menu', () => { const flag = ref(false) const switchFlag = () => { flag.value ? flag.value = false : flag.value = true } return { flag, switchFlag } })
import { useMenuStore } from '@/stores/menu' router.beforeEach((to, from, next) => { // 其它逻辑 // MUST const store = useMenuStore(); store.flag = false; next(); }) router.afterEach((to, from) => { // 其它逻辑 if (to.path === from.path) { const store = useMenuStore() store.flag = false } })