1, the preface


In a Vue project, there will certainly be a scenario where the same methods are used on different component pages, such as formatting times, file downloads, object deep copies, returning data types, copying text, and so on. At this point, we need to isolate common functions and provide them for global use. So how do we define a utility function class that we can use in the global environment? See the breakdown below.

PS: VUE of this paper is 2.6.12

2. The first way


Add directly to the Vue instance prototype

First open main.js, import the defined general method utils. Js file, then add it to the Vue instance using vue.prototype. $utils = utils

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')
Copy the code

Later, in the component page, if needed, this.$utils.xxx will do the job

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

Disadvantages:

  • Binding too many things can make the VUE instance too large
  • Use this every time

Advantages:

  • Define simple

Official Documentation

3. The second way


usewebpack.ProvidePluginIntroduced the global

You first import webpack and Path in vue.config, then define plugins in the configureWebpack object of module.exports to import the JS files you need

The complete vue.config.js configuration is as follows:

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.// Start the proxy
					pathRewrite: {
						'^/api': '/',},},}},plugins: [
			new webpack.ProvidePlugin({
        		UTILS: [path.resolve(__dirname, './src/utils/Utils.js'), 'default'].// Define the global function class
				TOAST: [path.resolve(__dirname, './src/utils/Toast.js'), 'default'].// Defines the global Toast popbox method
				LOADING: [path.resolve(__dirname, './src/utils/Loading.js'), 'default'] // Define the global Loading method}}})]Copy the code

Once defined, if you have ESlint in your project, you also need to add a Globals object to the.eslintrc.js file in the root directory and enable the property name of the defined global function class, otherwise an error will be reported that the property cannot be found.

module.exports = {
  root: true.parserOptions: {
    parser: 'babel-eslint'.sourceType: 'module'
  },
  env: {
    browser: true.node: true.es6: true,},"globals": {"UTILS": true."TOAST": true."LOADING": true
  }
  / /... Omit N lines of ESlint configuration
}
Copy the code

Once defined, restart the project and use it as follows:

computed: {
	playCount() {
		return (num) = > {
			UTILS is the defined global function class
			const count = UTILS.tranNumber(num, 0)
			return count
		}
	}
}
Copy the code

Disadvantages:

  • Not yet…

Advantages:

  • Team development cool

Official Documentation


If you think it is helpful, I am @pengduo, welcome to like and follow the comments; END

PS: on this page press F12, input document. In the console querySelectorAll (‘ like – BTN ‘) [0]. Click (), a surprise

The articles

  • Use NVM to manage node.js version and change NPM Taobao image source
  • More detailed! Vue’s nine ways of communication
  • Wechat small program to achieve search keyword highlighting
  • Env files are used in vUE to store global environment variables and configure vUE startup and package commands
  • More detailed! Vuex hands-on tutorials

Personal home page

  • CSDN
  • GitHub
  • Jane’s book
  • Blog garden
  • The Denver nuggets