Skip to content

Instantly share code, notes, and snippets.

@DesignHhuang
Created September 28, 2023 10:44
Show Gist options
  • Save DesignHhuang/09321a177e8bc17b7e73c8e279ec003e to your computer and use it in GitHub Desktop.
Save DesignHhuang/09321a177e8bc17b7e73c8e279ec003e to your computer and use it in GitHub Desktop.
有用的 Vue.js 自定义 Hook(1)
import { ref } from 'vue';
const getItem = (key, storage) => {
let value = storage.getItem(key);
if (!value) {
return null;
}
try {
return JSON.parse(value)
} catch (error) {
return value;
}
}
export const useStorage = (key, type = 'session') => {
let storage = null;
switch (type) {
case 'session':
storage = sessionStorage;
break;
case 'local':
storage = localStorage;
break;
default:
return null;
}
const value = ref(getItem(key, storage));
const setItem = (storage) => {
return (newValue) => {
value.value = newValue;
storage.setItem(key, JSON.stringify(newValue));
}
}
return [
value,
setItem(storage)
]
}
import { ref, onMounted, onUnmounted } from 'vue';
export function useWindowResize() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const handleResize = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
}
onMounted(() => {
window.addEventListener('resize', handleResize)
});
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
return {
width,
height
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment