Vue defines global variables and global methods, used in .vue files and .js files

Background: The syntax for using global variables is different between .vuefiles with suffixes and files with suffixes..js

.vueTemplate files can directly access the global objects mounted on the Vue instance, but ordinary .jsfiles cannot.

1. Define global variables

  const ssoServer = "https://iam.by.gov.cn/idp"; // 生产环境
  const ssoServerLogout = "https://iam.by.gov.cn/apphub/logout"; // 生产环境

  export default
  {
    
    
    ssoServer,
    ssoServerLogout
  }

What I define here are constants. Variables just replace const with let, and everything else is the same.

2. Mount global variables, main.js is the entry file of the Vue project, and mount global variables to the Vue instance in main.js.

import global_ from './config/Global' // 这个路径是相对于main.js的相对路径

Vue.prototype.GLOBAL = global_

3. Access global variables

3.1 Access through Vue.prototype object

import Vue from 'vue'

let a = Vue.prototype.GLOBAL.ssoServer

This way of writing can be used in both .vue files and .js files.

3.2 Access through this keyword

let a = this.GLOBAL.ssoServer

This way of writing can only be used in .vue files.

.vueIn the template file, thiskeywords can access Vue.prototypeall objects mounted on it, so writing thisis equivalent to writing Vue.prototype.

4. Define global methods

Use the export function syntax in any .js file to make this method a global method.

export function 个人号码加密 (号码) {
    
    
  let length = 号码.length
  if (length < 8) return 号码
  let 开始加密位 = length / 2 - length / 5
  let 结束加密位 = 开始加密位 + length / 3
  let 加密位数 = 结束加密位 - 开始加密位 + 1
  let 加密结果 = 号码.substring(0, 开始加密位)
  for (let i = 0; i < 加密位数; i++) {
    
    
    加密结果 += '*'
  }
  加密结果 += 号码.substring(结束加密位, length)
  return 加密结果
}

5. Use global methods

It can be called in other .js and .vue files. The calling syntax is the same.

import * as common from '@/utils/common' 
// @/utils为路径, common为js文件名

let 身份证号码 = "44132319960617502X"
let 身份证号码加密 = common.个人号码加密(身份证号码)

Global methods do not need to be mounted on Vuethe instance, importthey can be accessed directly by JS files.

Guess you like

Origin blog.csdn.net/qiaoqiaohong/article/details/122703117