Recently, I have involved JS global variables in the middle of learning. It is not so much a global variable of VUE, but rather a global variable of modular JS development.
1. Global variable special module
It is to organize and manage these global quantities with a specific module, and import the module where it needs to be referenced.
Global variable dedicated module
<script type="text/javascript"> const colorList = [ '#F9F900', '#6FB7B7', '#9999CC', '#B766AD', '#B87070', '#FF8F59', '#FFAF60', '#FFDC35', '#FFFF37', '#B7FF4A', '#28FF28', '#1AFD9C', '#00FFFF', '#2894FF', '#6A6AFF', '#BE77FF', '#FF77FF', '#FF79BC', '#FF2D2D', '#ADADAD' ] const colorListLength = 20 function getRandColor () { var tem = (() * colorListLength) return colorList[tem] } export default { colorList, colorListLength, getRandColor } </script>
The variables in the module are exposed by export. When it is necessary to use other places, you can introduce the module global.
Modules that require global variables
<template> <ul> <template v-for="item in mainList"> <div class="projectItem" :style="'box-shadow:1px 1px 10px '+ getColor()"> <router-link :to="'project/'+"> ![]() <span>{{}}</span> </router-link> </div> </template> </ul> </template> <script type="text/javascript"> import global_ from 'components/tool/Global' export default { data () { return { getColor: global_.getRandColor, mainList: [ { id: 1, img: require('../../assets/'), title: 'Login interface' }, { id: 2, img: require('../../assets/'), title: 'Homepage' } ] } } } </script> <style scoped type="text/css"> .projectItem { margin: 5px; width: 200px; height: 120px; /*border:1px soild;*/ box-shadow: 1px 1px 10px; } .projectItem a { min-width: 200px; } .projectItem a span { text-align: center; display: block; } </style>
2. The global variable module is mounted in.
Same as above, add the following code to the program entrance
import global_ from './components/tool/Global' = global_
After mounting, at the module that needs to reference the global quantity, there is no need to import the global quantity module. You can directly use this to reference it, as follows:
<script type="text/javascript"> export default { data () { return { getColor: , mainList: [ { id: 1, img: require('../../assets/'), title: 'Login interface' }, { id: 2, img: require('../../assets/'), title: 'Homepage' } ] } } } </script>
3. Use VUEX
Vuex is a state management model developed specifically for applications. It uses centralized storage to manage the state of all components of the application. Therefore, the global quantity can be stored. Because Vuex is a bit cumbersome, it feels like killing a chicken and using a slaughter. It is not considered necessary.
Link:vuex official introduction
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.