Vue3常用功能实现

187 阅读2分钟

一、最简单方法制作主题

(1)在thmem.css中先定义好全局样式与全部颜色

:root {
    /* 默认主题色:默认为管理员 */
    --theme-color: #0563BE;
    --adminis-theme-color: #0563BE;
    --admin-theme-color: #FF9746;

    /* 默认主题边框色 */
    --theme-box-shadow-color: 0px 0px 6px #70A7DB40;
    
    --adminis-theme-box-shadow-color: 0px 0px 6px #70A7DB40;
    --admin-theme-box-shadow-color: 0px 0px 6px #FF974646;

    /* 默认渐变色:默认为管理员 */
    --theme-color-gradual-right: linear-gradient(to right, #116BC2, #70A7DB);
    --theme-color-gradual-bottom: linear-gradient(to bottom, #116BC2, #70A7DB);
    --theme-color-gradual-bg: linear-gradient(140deg, #FFFFFF 0%, #F6F6F6 50%, #F6F6F6 75%);

    --adminis-theme-color-gradual-right: linear-gradient(to right, #116BC2, #70A7DB);
    --adminis-theme-color-gradual-bottom: linear-gradient(to bottom, #116BC2, #70A7DB);
    --adminis-theme-color-gradual-bg: linear-gradient(140deg, #FFFFFF 0%, #F6F6F6 50%, #F6F6F6 75%);
    
    --admin-theme-color-gradual-right: linear-gradient(to right, #FF9746, #FFB141);
    --admin-theme-color-gradual-bottom: linear-gradient(to bottom, #FF9746, #FFB141);
    --admin-theme-color-gradual-bg: linear-gradient(140deg, #FFFFFF 0%, #F6F6F6 50%, #F6F6F6 75%);
}

(2)当选中时,进行变量替换即可。


/* 得到root颜色 */
export const getColer = (data: string) => getComputedStyle(document.documentElement).getPropertyValue(data)

/*  设置 */
export const onColer = (original: string, setup: string) => {
    document.documentElement.style.setProperty(original, getColer(setup))
}

/* 执行主题切换 */
export const setColer = (name: string) => {
    /* 切换渐变色 */
    onColer('--theme-color-gradual-right', `--${name}-theme-color-gradual-right`)
    /* 背景 */
    onColer('--theme-color-gradual-bg', `--${name}-theme-color-gradual-bg`)
    /* 边框色 */
    onColer('--theme-box-shadow-color', `--${name}-theme-box-shadow-color`)
    /* 主题色 */
    onColer('--theme-color', `--${name}-theme-color`)
}

二、对svg进行组件化,并使之颜色可控制

import { ref } from 'vue'
import { defineStore } from 'pinia'
export default defineStore('counter', () => {
    //保存颜色
    const color = ref('#0563BE')
    //颜色控制
    const colorAcion = ref({
    u1: true,
    u2: true,
} as { [key: string]: boolean })
    //传入颜色
    const increment = (data: string) => {
        color.value = data
        console.log(color.value)
    }
    return { color, colorAcion, increment }
})
<script setup lang="ts">
/* 组件通讯 */
import { storeToRefs } from 'pinia'
/* 实例化 */
import useDemoStore from "@/stores/svg";
/* 解构 */
const { color, colorAcion } = storeToRefs(useDemoStore())
</script>
<template>
    <svg width="25" height="20" viewBox="0 0 25 20" fill="none" xmlns="http://www.w3.org/2000/svg">
    <!--d里的矢量参数,此处以xxx代替-->
        <path
            d="xxx"
            :fill="colorAcion.u1 ? color : '#ffffff'" />
    </svg>
</template>

三、上传的图片立即挂载并显示

URL.createObjectURL(item.file)

四、缓存

永久缓存localStorage

//获取
const jsondata = window.localStorage.getItem('key')
 if (jsondata != null) {
   const key = JSON.parse('key')
 }
//写入
  window.localStorage.setItem('key', JSON.stringify('val'))

临时缓存sessionStorage

//获取
  const jsondata = sessionStorage.getItem('token')
  if (jsondata != null) {
    const token = JSON.parse(jsondata)
  }
//写入
sessionStorage.setItem('token', JSON.stringify('val'))

五、后端数据转格式

/**
 * time特殊时间格式
 * type时间分割符
 */
const resTime = (time: string, type: string) => {
  const date = new Date(time)
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  const min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  const sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  const times = `${date.getFullYear()}${type}${month}${type}${day} ${hours}:${min}:${sec}`
  return times
}
resTime('time-size','/')

六、分页数据

import { ref, reactive, onBeforeMount } from 'vue'
//分页控制
const data = reactive({
  current_page: 1, //当前页数
  article_page: 9, //每页显示
  total: gdata.length  //总页数
})
/* 表数据 */
const sdata = ref<any>([])
      <el-pagination
        v-model:current-page="data.current_page"
        v-model:page-size="data.article_page"
        layout="prev, pager, next, jumper"
        :total="data.total"
        @current-change="handleCurrentChange"
        :hide-on-single-page="pagination"
      >
      </el-pagination>
const handleCurrentChange = (value: number) => {
  //获取当前页码
  data.current_page = value
  if (data.current_page == 1) {
    tablesAction()
    return
  }
  //初始化
  sdata.value = []
  /* 截取 */
  /* 脚下标计算 */
  const l = data.current_page * data.article_page - data.article_page
  const s = data.current_page * data.article_page - 1
  //是从2开始的  2就是   10开始
  //  3 就是 0-9  10-20
  sdata.value = gdata.slice(l, s)
}
const pagination = ref(false)
onBeforeMount(() => {
  tablesAction()
})
/* c初始化 */
const tablesAction = () => {
  //先把数据清空
  sdata.value = []
  if (gdata.length > data.article_page) {
    pagination.value = false
    sdata.value = gdata.slice(0, data.article_page - 1)
  } else {
    pagination.value = true
    console.log(pagination.value)
    sdata.value = gdata
  }
}

七、前端格式转化

export const dateDay = (type:string) => {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const M = month < 10 ? `0${month}` : `${month}`
    const D = day < 10 ? `0${day}` : `${day}`
    return `${year}${type}${M}${type}${D}`
}

八、默认按钮简单方法

const NameMap: ClassType = {
    '0': '全部',
    '1': '1教',
    '2': '2教',
    '3': '3教'
}
const isButtonClicked = (val: number) => {
    if (retval == val) {
        return true
    }
    return false
}
onMounted(() => {
    selete(0)
})
<button 
v-for="val of Object.keys(NameMap).length"
:class="{ 'default-clicked': isButtonClicked(val - 1) }" 
@click="selete(val - 1)">
{{ NameMap[val - 1] }}
</button>
.default-clicked {
        background-color: #007bff ;
        color: #fff ;
        box-shadow: 0px 0px 5px rgba(87, 85, 85, 0.11);
}

九、过渡动画

<script setup>
import { ref } from 'vue'

const show = ref(true)
</script>

<template>
  <button @click="show = !show">Toggle</button>
  <Transition>
    <p v-if="show">hello</p>
  </Transition>
</template>

<style>
.v-enter-active,
.v-leave-active {
  /* 过渡的时间0.3s 建议0.3-0.5 */
  transition: opacity 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>

十、固定组件

<script>
    import { ref, onMounted, onUnmounted, watchEffect } from 'vue';
//存储
   const container = ref\<HTMLElement | null>(null);
//存储
   const button = ref\<HTMLElement | null>(null);
//方法
   const handleScrollMenu = () => {
   if (!container.value || !button.value) {
      return;
   }
     const { top } = container.value.getBoundingClientRect();
     const { height: buttonHeight } = button.value.getBoundingClientRect();
     button.value.style.position = top < 0 ? 'fixed' : 'static';
     button.value.style.top = top < 0 ? '0' : '';
     button.value.style.width = top < 0 ? `${container.value.clientWidth}px` : '';
     container.value.style.paddingTop = top < 0 ? `${buttonHeight}px` : '0';
   };
//初始化
   onMounted(() => {
      window.addEventListener('scroll', handleScrollMenu);
   })
//消除
   onUnmounted(() => {
     window\.removeEventListener('scroll', handleScrollMenu);
   })   
</script>
<template>
    <div class="container" ref="container">
    <div class="button" ref="button">
    <button>
    全部
    </button>
    </div>
    </div>
</template>