文章已阅读
 

全局变量

1.直接在main.js中通过prototype定义

1
Vue.prototype.accessToken = 'xxx'

在页面中调用:this.accessToken
这种方法简单但是,当需要定义变量很多的时候,管理就很繁杂,这个时候就不宜使用。

2.定义一个通用js文件,在文件中定义通用变量(通过export default 暴露),最后引入(import)调用;

定义:

1
2
3
4
5
//universal.js
const accessToken ='xxx'
export default {
accessToken ,
}

调用(可以在需要的页面引入,也可以在main.js中引入)

(1)在需要的页面直接引入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div>{ Token }</div>
</template>

<script>
import universal from '../universal' // 引入模块
export default {
data () {
return {
Token: universal.accessToken //获取方法定义的变量
}
}
}
</script>

(2)从main.js中引入

1
2
import universal from '../universal' // 引入模块
Vue.prototype.universal = universal

后在页面调用:this.universal.accessToken

全局函数

1.在main.js中直接定义一个函数

1
Vue.prototype.getToken = function () {}

后在组件中调用:this.getToken()

2.定义一个js文件,然后挂载到main.js中

定义的js文件:universal.js

1
2
3
4
5
6
7
8
9
/*配置通用方法, 新增方法请写备注*/
exports.install = function (Vue, options) {
/*判断是不是图片*/
Vue.prototype.isImage = function (fileName) {
if (typeof fileName !== 'string') return;
let name = fileName.toLowerCase();
return name.endsWith('.png') || name.endsWith('.jpeg') || name.endsWith('.jpg') || name.endsWith('.png') || name.endsWith('.bmp');
}
}

挂载到 main.js中

1
2
import Universal from './assets/theme/js/universal'
Vue.use(Universal)

在页面中调用其中的某个方法:this.isImage(‘xxx’)

2022-10-08

浏览 |

© 2023 南疆 with help from Hexo and Twitter Bootstrap. Theme by Freemind.

container-narrow -->