两种方式配置vue全局方法

1,前言


在Vue项目开发中,肯定会有这样一个场景:在不同的组件页面用到同样的方法,比如格式化时间,文件下载,对象深拷贝,返回数据类型,复制文本等等。这时候我们就需要把常用函数抽离出来,提供给全局使用。那如何才能定义一个工具函数类,让我们在全局环境中都可以使用呢?请看下文分解。

PS:本文vue为2.6.12

2,第一种方式


直接添加到Vue实例原型上

首先打开main.js,通过import引入定义的通用方法utils.js文件,然后使用Vue.prototype.$utils = utils,添加到Vue实例上

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import utils from './utils/Utils'

Vue.prototype.$utils = utils

new Vue({
	router,
	store,
	render: h => h(App)
}).$mount('#app')

之后,在组件页面中,需要使用的话,就是this.$utils.xxx就行了

methods: {
	fn() {
		let time = this.$utils.formatTime(new Date())
	}
}

缺点:

  • 绑定的东西多了会使vue实例过大
  • 每次使用都要加上this

优点:

  • 定义简单

官方说明文档

3,第二种方式


使用webpack.ProvidePlugin全局引入

首先在vue.config中引入webpackpath,然后在module.exportsconfigureWebpack对象中定义plugins,引入你需要的js文件

完整的vue.config.js配置如下:

const baseURL = process.env.VUE_APP_BASE_URL
const webpack = require('webpack')
const path = require("path")

module.exports = {
	publicPath: './',
	outputDir: process.env.VUE_APP_BASE_OUTPUTDIR,
	assetsDir: 'assets',
	lintOnSave: true,
	productionSourceMap: false,
	configureWebpack: {
		devServer: {
			open: false,
			overlay: {
				warning: true,
				errors: true,
			},
			host: 'localhost',
			port: '9000',
			hotOnly: false,
			proxy: {
				'/api': {
					target: baseURL,
					secure: false,
					changeOrigin: true, //开启代理
					pathRewrite: {
						'^/api': '/',
					},
				},
			}
		},
		plugins: [
			new webpack.ProvidePlugin({
        		UTILS: [path.resolve(__dirname, './src/utils/Utils.js'), 'default'], // 定义的全局函数类
				TOAST: [path.resolve(__dirname, './src/utils/Toast.js'), 'default'], // 定义的全局Toast弹框方法
				LOADING: [path.resolve(__dirname, './src/utils/Loading.js'), 'default'] // 定义的全局Loading方法
      		})
		]
	}
}

这样定义好了之后,如果你项目中有ESlint,还需要在根目录下的.eslintrc.js文件中,加入一个globals对象,把定义的全局函数类的属性名启用一下,不然会报错找不到该属性。

module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint',
    sourceType: 'module'
  },
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  "globals":{
    "UTILS": true,
    "TOAST": true,
    "LOADING": true
  }
  // ...省略N行ESlint的配置
}

定义好了之后,重启项目, 使用起来如下:

computed: {
	playCount() {
		return (num) => {
			// UTILS是定义的全局函数类
			const count = UTILS.tranNumber(num, 0)
			return count
		}
	}
}

缺点:

  • 还没发现...

优点:

  • 团队开发爽

官方说明文档

如果看了觉得有帮助的,我是@上进的鹏多多,欢迎 点赞 关注 评论;END


PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦


面向百度编程

公众号

weixinQRcode.png

往期文章

个人主页

posted @ 2021-09-13 10:46  鹏多多  阅读(1450)  评论(0编辑  收藏  举报