Background: The syntax for using global variables is different between .vue
files with suffixes and files with suffixes..js
.vue
Template files can directly access the global objects mounted on the Vue instance, but ordinary .js
files 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.
.vue
In the template file, this
keywords can access Vue.prototype
all objects mounted on it, so writing this
is 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.个人号码加密(身份证号码)