nuxt
Version:
[](https://nuxt.com)
40 lines (39 loc) • 1.35 kB
JavaScript
import { isRef, toRef } from "vue";
import { useNuxtApp } from "../nuxt.js";
const useStateKeyPrefix = "$s";
export function useState(...args) {
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
if (typeof args[0] !== "string") {
args.unshift(autoKey);
}
const [_key, init] = args;
if (!_key || typeof _key !== "string") {
throw new TypeError("[nuxt] [useState] key must be a string: " + _key);
}
if (init !== void 0 && typeof init !== "function") {
throw new Error("[nuxt] [useState] init must be a function: " + init);
}
const key = useStateKeyPrefix + _key;
const nuxt = useNuxtApp();
const state = toRef(nuxt.payload.state, key);
if (state.value === void 0 && init) {
const initialValue = init();
if (isRef(initialValue)) {
nuxt.payload.state[key] = initialValue;
return initialValue;
}
state.value = initialValue;
}
return state;
}
export function clearNuxtState(keys) {
const nuxtApp = useNuxtApp();
const _allKeys = Object.keys(nuxtApp.payload.state);
const _keys = !keys ? _allKeys : typeof keys === "function" ? _allKeys.filter(keys) : Array.isArray(keys) ? keys : [keys];
for (const _key of _keys) {
const key = useStateKeyPrefix + _key;
if (key in nuxtApp.payload.state) {
nuxtApp.payload.state[key] = void 0;
}
}
}