Two ways to configure Vue global methods

Two ways to configure Vue global methods

1. Introduction

In the development of Vue projects, there will definitely be a scenario where the same method is used in different component pages, such as formatting time, file downloading, deep copying of objects, returning data types, copying text, and so on. At this time, we need to extract the commonly used functions and provide them for global use. So how can we define a tool function class that we can use in the global environment? Please see the breakdown below.

PS: This article uses vue 2.6.12

2. The first method

Add directly to the Vue instance prototype

First open main.js, import the common method utils.js file defined by import, and then use Vue.prototype.$utils = utils to add it to the Vue instance

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')

After that, if you need to use it in the component page, just use this.$utils.xxx

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

shortcoming:

  • Too many bindings will make the Vue instance too large
  • Add this every time you use it

advantage:

  • Simple definition

Official documentation

3. The second method

Use webpack.ProvidePlugin to import globally

First, introduce webpack and path in vue.config, then define plugins in the configureWebpack object of module.exports and introduce 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, //Open proxypathRewrite: {
      '^/api': '/',
     },
    },
   }
  },
  plugins: [
   new webpack.ProvidePlugin({
          UTILS: [path.resolve(__dirname, './src/utils/Utils.js'), 'default'], // Defined global function class TOAST: [path.resolve(__dirname, './src/utils/Toast.js'), 'default'], // Defined global Toast pop-up box method LOADING: [path.resolve(__dirname, './src/utils/Loading.js'), 'default'] // Defined global Loading method })
  ]
 }
}

After defining it like this, if you have ESlint in your project, you also need to add a globals object to the .eslintrc.js file in the root directory to 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}

After defining it, restart the project and use it as follows:

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

shortcoming:

  • Haven't found yet...

advantage:

  • Team development fun

Official documentation

Summarize

This concludes this article on two ways to configure vue global methods. For more information on configuring vue global methods, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue defines global variables and global methods
  • A brief discussion on Vue's custom global components and using them through the global method Vue.use()
  • Example code of mounting vue component to global method
  • Vue custom global method, introduction to its use in components

<<:  How to enable the root account in Ubuntu 20.04

>>:  Mariadb remote login configuration and problem solving

Recommend

HTML form tag tutorial (1):

Forms are a major external form for implementing ...

IE9beta version browser supports HTML5/CSS3

Some people say that IE9 is Microsoft's secon...

Hyperlink icon specifications: improve article readability

1. What is the hyperlink icon specification ?<...

JS implements WeChat's "shit bombing" function

Hello everyone, I am Qiufeng. Recently, WeChat ha...

How to implement https with nginx and openssl

If the server data is not encrypted and authentic...

How to solve "Unable to start mysql service error 1069"

Today, when I was on the road, a colleague sent m...

JavaScript Dom implements the principle and example of carousel

If we want to make a carousel, we must first unde...

Detailed explanation of keywords and reserved words in MySQL 5.7

Preface The keywords of MySQL and Oracle are not ...

Detailed explanation of MySQL's Seconds_Behind_Master

Table of contents Seconds_Behind_Master Original ...

VMware Workstation virtual machine installation operation method

Virtual machines are very convenient testing soft...

A Deep Dive into the MySQL InnoDB Storage Engine

Preface In MySQL, InnoDB belongs to the storage e...

WeChat applet implements fixed header and list table components

Table of contents need: Function Points Rendering...

Implementation of Nginx load balancing/SSL configuration

What is load balancing? When a domain name points...

How to use iostat to view Linux hard disk IO performance

TOP Observation: The percentage of CPU time occup...