赞
踩
在项目中,经常有些函数和变量是需要复用,比如说网站服务器地址,从后台拿到的:用户的登录 token, 用户的地址信息等,这时候就需要设置一波全局变量和全局函数,由于项目不大,用到的共有变量及函数也不多,所以用其他方式替代使用 Vuex
原理:
设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用 export default
暴露出去,在 main.js
里面使用 Vue.prototype
挂载到 vue
实例上面或者在其它地方需要使用时,引入该模块便可
全局变量模块文件:
global.js
文件
const TOKEN = '1HTiBfaPmaPbek8K7RMEBIg'
const SECURITY_KEY = '3i6VAGkjIUBg4wAV'
const ORDER_STATUS = {
0: { text: '处理中', color: 'warning' },
1: { text: '成功', color: 'success' },
2: { text: '失败', color: 'danger' },
3: { text: '删除', color: 'info' }
}
export default
{
TOKEN,
SECURITY_KEY,
ORDER_STATUS
}
使用:
<template> <div>{{ token }}</div> </template> <script> import _global_ from '../common/global.js'//引用模块进来 export default { name: 'demo', data () { return { //将全局变量赋值到data里面,也可以直接使用_global_.TOKEN token: _global_.TOKEN } } } </script>
main.js
文件里面,将上面那个 global.js
文件挂载到 Vue.prototype
main.js
入口文件引入
import _global_ from './common/global.js' //引用文件
Vue.prototype.GLOBAL = _global_ //挂载到Vue实例上面
接着在整个项目中不需要再通过引用 global.js
模块文件,直接通过 this
就可以直接访问 Global
文件里面定义的全局变量
<template>
<div>{{ token }}</div>
</template>
<script>
export default {
name: 'text',
data () {
return {
token:this.GLOBAL.TOKEN, //直接通过this访问全局变量。
}
}
}
</script>
原理:
新建一个模块文件,然后在 main.js
里面通过 Vue.prototype
将函数挂载到 Vue
实例上面,通过 this.
函数名,来运行函数
main.js
里面直接写函数(当需要全局的函数不多时可以使用)Vue.prototype.changeData = function (){//changeData是函数名
alert('执行成功');
}
组件中调用:
//直接通过this运行函数
this.changeData();
main.js
上面。
base.js
文件,文件位置可以放在跟main.js
同一级,方便引用
exports.install = function (Vue, options) {
Vue.prototype.text1 = function (){//全局函数1
alert('执行成功1');
};
Vue.prototype.text2 = function (){//全局函数2
alert('执行成功2');
};
};
main.js
入口文件:
import base from './base' //引用
Vue.use(base); //将全局函数当做插件来进行注册
组件里面调用:
this.text1();
this.text2();
global.js
文件:
export const TOKEN = '1HTiBfaPmaPbek8K7RMEBIg'
export const SECURITY_KEY = '3i6VAGkjIUBg4wAV'
export const testFun= (t) => {
alert('testFun:' + t)
}
export const testFun2= () => {
alert('testFun2')
}
main.js
入口文件引入:
import * as globalData from '../common/global.js'
Vue.prototype.GLOBAL = globalData
Vue文件
内使用 this.
引用:
<template> <div @click="handleClick">{{ token }}</div> </template> <script> export default { name: 'text', data () { return { token:this.GLOBAL.TOKEN, //直接通过this访问全局变量。 } }, methods: {e handleClick(e){ this.GLOBAL.testFun(e.target.innerText) // 输出 -----------> testFun:1HTiBfaPmaPbek8K7RMEBIg } } } </script>
关于在 Vuejs
项目中如何定义全局变量 全局函数让组件共享数据 → 替代 vuex
的数据共享就说到这里,如有错误欢迎指出~
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。