Created
September 28, 2023 10:44
-
-
Save DesignHhuang/09321a177e8bc17b7e73c8e279ec003e to your computer and use it in GitHub Desktop.
有用的 Vue.js 自定义 Hook(1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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