Vue2项目中的开发技巧

289 阅读1分钟

一,工具类utils挂载到vue中

项目中我们经常会封装一些工具方法(常用的方法)到src/utils文件夹中,然后通过导出(export)/引入(import)的方式去使用我们的工具集方法。这导致我们每次使用的时候都要导入。

我们可以通过把utils中的模块区分,在集成到index中,然后把集成的文件挂载到vue的原型上

在我们的utils中新建一个常用的工具集(比如时间处理)

// moment.js
import moment from 'moment'
const formatTime = function(time, format) {
  time = new Date(time)
  format = format || 'YYYY-MM-DD'

  function tf(i) {
    return (i < 10 ? '0' : '') + i
  }
  return format.replace(/YYYY|MM|DD|hh|mm|ss|WW/g, function(a) {
    switch (a) {
      case 'YYYY':
        return tf(time.getFullYear())
      case 'MM':
        return tf(time.getMonth() + 1)
      case 'DD':
        return tf(time.getDate())
      case 'mm':
        return tf(time.getMinutes())
      case 'hh':
        return tf(time.getHours())
      case 'ss':
        return tf(time.getSeconds())
      case 'WW':
        return ['日', '一', '二', '三', '四', '五', '六'][time.getDay()]
    }
  })
}
export default { formatTime }

在utils中新建一个index.js文件

/**
 * 整合模块
 * @desc 用于直接挂在到vue原型上
 * @auther tanqf
 * @date 2022/04/26
 */
import moment from './validate' 
export default { moment }

最后 我们可以在main.js中挂载到vue中原型

import $utils from '@/utils/index'
Vue.prototype.$utils = $utils 

在页面中,可以通过以下方式调用

this.$utils.[模块].[方法]
如:this.$utils.moment.formatTime(参数)

二,公共组件全局挂载和UI库组件按需引入

1,全局组件挂载

一般项目中复用性高的组件,我们都会把它抽离到src/components 文件夹中,但是每次我们要使用的时候,都需要把组件引入,或者写个文件去把他批量引入然后注册到vue上,其实我们可以通过遍历文件的形式,让他批量注册

在components下新建一个common文件夹来存放我们要批量注册的组件(在该文件夹中的组件都会被批量注册到vue中)

在components下新建一个publicComponentsInstall.js文件

// 自动注册common文件夹下的组件
export default {
  install(Vue) {
    // 批量注册公用组件
    const components = require.context('@/components/common', false, /.vue$/)
    components.keys().map(path => {
      const fileName = path.replace(/(.*/)*([^.]+).*/ig, '$2') // 获取组件文件名
      Vue.component(fileName, components(path).default || components(path))
    })
  }
}

在main.js中添加

import publicComponentsInstall from '@/components/publicComponentsInstall'

2,ui组件库按需引入

我们在使用市面上的一些组件库(ui库)的时候,都习惯全量引入,其实通过webpack打包查看大小(查看方式),会发现,ui库的包其实占了不少内存

下面以element-ui库为例子,配置项目中的按需引入

在components下新建一个elementComponentsInstall.js文件

// 按需加载element组件
import { Input, Button, Select, Option, Notification, Message, Pagination, Dialog, Loading, Tooltip, Card, Form, FormItem, Upload } from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
export default {
  install(Vue) {
    Vue.use(Input)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Button)
    Vue.use(Pagination)
    Vue.use(Dialog)
    Vue.use(Loading)
    Vue.use(Tooltip)
    Vue.use(Card)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Upload)

    Vue.prototype.$message = Message
    Vue.prototype.$notify = Notification
  }
}

然后再main.js中引用

import elementComponentsInstall from '@/components/elementComponentsInstall'

三,vue项目如何做换肤?

我的另外一篇文章有介绍如何对一个项目做换肤需求(传送),但是该方案是基于less,实现起来可能有点繁琐,下面我们用另一种方式实现换肤功能

在项目assets/下新建styles文件夹,该文件夹表示项目中的公共样式文件可以存放于此。

在styles下新建theme文件,添加一个themes.js和index.js文件

我们先配置好我们的主题色文件themes.js

// 一套默认主题以及一套暗黑主题
export const themes = {
  default: {
    primaryColor: `${74}, ${144},${226}`,
    primaryTextColor: `${0}, ${0},${0}`,
  },
  dark: {
    primaryColor: `${0},${0},${0}`,
    primaryTextColor: `${255},${255},${255}`,
  },
};

在新建的index.js中

import { themes } from "./themes";
// 修改页面中的样式变量值
const changeStyle = (obj) => {
  for (let key in obj) {
    document
      .getElementsByTagName("body")[0]
      .style.setProperty(`--${key}`, obj[key]);
  }
};
// 改变主题的方法
export const setTheme = (themeName) => {
  localStorage.setItem("theme", themeName); // 保存主题到本地,下次进入使用该主题
  const themeConfig = themes[themeName];
  // 如果有主题名称,那么则采用我们定义的主题
  if (themeConfig) {
    localStorage.setItem("primaryColor", themeConfig.primaryColor); // 保存主题色到本地
    localStorage.setItem("primaryTextColor", themeConfig.primaryTextColor); // 保存文字颜色到本地
    changeStyle(themeConfig); // 改变样式
  } else {
    let themeConfig = {
      primaryColor: localStorage.getItem("primaryColor"),
      primaryTextColor: localStorage.getItem("primaryTextColor"),
    };
    changeStyle(themeConfig);
  }
};

setTheme方法通过识别传入的主题变量名称,去找出themes中对应的主题,然后通过changeStyle把主题的颜色全部注册css变量到body中,然后我们在要改变的位置通过下面的方式去使用定义的主题下的颜色值等

<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: rgba(@primaryTextColor, 1);
  background-color: rgba(@primaryColor, 1);
}
</style>

调用setTheme方法

  import { setTheme } from '@/assets/styles/theme/index'

  const changeTheme = (val: string) => {
    switch (val) {
      case 'default':
        setTheme(val)
        break
      case 'dark':
        setTheme(val)
        break
      case 'custom':
        customTheme()
        break
      default:
        break
    }
  }

四,待更新...