Vue: localStorage封装

 

App.vue

<template>
  <div id="heart" @click="toggleFlag">
    <span :class="{active:flag}"></span>
    <span :class="{active:flag}"></span>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { getItem, setItem } from '@/utils/localStorage'


const flag = ref<boolean>(true)
const toggleFlag = () => {
  flag.value = ! flag.value
  setItem('flag', flag.value)
}
onMounted(() => {
  flag.value = getItem('flag', true)
})
</script>

<style lang="less">
.active {
  background-color: red !important;
}

#heart > span {
  background-color: palegreen;
}

#heart {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  height: 150px;
  /* background-color: palegreen; */
  animation: heart 1s linear 0s infinite;
}

#heart > span:nth-child(1) {
  position: absolute;
  width: 100px;
  height: 150px;
  border-radius: 50px 50px 0 0;
  transform: rotate(-45deg);
  transform-origin: 0 100%;
  margin-left: 50px;
}

#heart > span:last-child {
  position: absolute;
  width: 100px;
  height: 150px;
  border-radius: 50px 50px 0 0;
  transform: rotate(45deg);
  transform-origin: 100% 100%;
  margin-left: -50px;
}

@keyframes heart {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(0.8);
  }

  100% {
    transform: scale(1);
  }
}
</style>

 

localStorage.ts

const namespace: string = 'zax'

export function setItem(key: string, value: any) {
  console.log(key, value)
  let storage = window.localStorage.getItem(namespace)

  if (! storage) {
    storage = {}
  } else {
    storage = JSON.parse(storage) || {}
  }

  storage[key] = value
  window.localStorage.setItem(namespace, JSON.stringify(storage))
}

export function getItem(key: string, defaultValue: any) {
  let storage = window.localStorage.getItem(namespace)
  if (! storage) {
    storage = {key: defaultValue}
    window.localStorage.setItem(namespace, JSON.stringify(storage))
    return defaultValue
  }

  storage = JSON.parse(storage)

  return storage[key]

}

 

posted @ 2022-03-28 15:11  ascertain  阅读(272)  评论(0编辑  收藏  举报