Vue2 global variable setting method
Recently, I learned about js global variables in VUE. JS. It is not so much a global variable in VUE as a global variable in modular JS development.
1. dedicated global variable Module
It is to organize and manage these global volumes in a specific module. You can import them to the module where they need to be referenced.
Global. vue
<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 = 20function getRandColor () { var tem = Math.round(Math.random() * colorListLength) return colorList[tem]}export default{ colorList, colorListLength, getRandColor}</script>
The variables in the module are exposed using the export. When the variables need to be used elsewhere, you can introduce the module global.
Html5.vue
<Template> <ul> <template v-for = "item in mainList"> <div class = "projectItem": style = "'box-shadow: 1px 1px 10px '+ getColor () "> <router-link: to =" 'Project/' + item. id ">! [] (Item. img) <span> {item. title }}</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/rankIcon.png '), title: 'logon interface'}, {id: 2, img: require ('.. /.. /assets/rankIndex.png '), 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. Mount the global variable module to Vue. prototype.
Global. js is the same as above. Add the following code to main. js at the program entry.
import global_ from './components/tool/Global'Vue.prototype.GLOBAL = global_
After mounting, you do not need to import the global volume module to reference the global volume module. You can directly use this to reference it, as shown below:
<Script type = "text/javascript"> export default {data () {return {getColor: this. GLOBAL. getRandColor, mainList: [{id: 1, img: require ('.. /.. /assets/rankIcon.png '), title: 'logon interface'}, {id: 2, img: require ('.. /.. /assets/rankIndex.png '), title: 'homepage'}] }}</script>
3. Use VUEX
Vuex is a State Management Mode Designed for Vue. js applications. It uses centralized storage to manage the status of all components of an application. Therefore, the global volume can be stored. Because Vuex is a little complicated, it feels a little cool. I think it is unnecessary.
The above vue2 global variable setting method is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.