Method: Set up a dedicated global variable module file. Define the initial state of some variables in the module, expose it with "export default", and use "Vue.prototype" in "main.js" to mount it. When you need to use it on a vue instance or elsewhere, just introduce this module.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
Set a dedicated global variable module file, define some initial states of variables in the module, expose them with export default, in main. Use Vue.prototype in js to mount it on the vue instance or when it needs to be used elsewhere, just introduce this module.
Global.vue file:
<script> const serverSrc='www.baidu.com'; const token='12345678'; const hasEnter=false; const userSite="中国钓鱼岛"; export default { userSite,//用户地址 token,//用户token身份 serverSrc,//服务器地址 hasEnter,//用户登录状态 } </script>
Reference the global variable module file where needed, Then get the global variable parameter value through the variable name in the file.
Use in text1.vue component:
<template> <div>{{ token }}</div> </template> <script> import global_ from '../../components/Global'//引用模块进来 export default { name: 'text', data () { return { token:global_.token,//将全局变量赋值到data里面,也可以直接使用global_.token } } } </script> <style scoped> </style>
In the main.js file at the program entrance, mount the above Global.vue file to Vue.prototype.
import global_ from './components/Global'//引用文件 Vue.prototype.GLOBAL = global_//挂载到Vue实例上面
Then there is no need to reference the Global.vue module file in the entire project. You can directly access the global variables defined in the Global file through this.
text2.vue:
<template> <div>{{ token }}</div> </template> <script> export default { name: 'text', data () { return { token:this.GLOBAL.token,//直接通过this访问全局变量。 } } } </script> <style scoped> </style>
Related recommendations: "vue.js Tutorial"
The above is the detailed content of How to customize variables globally in vuejs. For more information, please follow other related articles on the PHP Chinese website!