How to set global variables in vue2? (detailed tutorial)

亚连
Release: 2018-05-31 15:24:56
Original
3802 people have browsed it

Below I will share with you an article on how to set vue2 global variables. It has a good reference value and I hope it will be helpful to everyone.

Recently, while learning VUE.js, JS global variables are involved. Rather than being VUE’s global variables, it is better to say they are global variables for modular JS development.

1. Special module for global variables

uses a specific module to organize and manage these global variables. You can import this module wherever you need to reference it. good.

Special module for global variables Global.vue

Copy after login

The variables in the module are exposed through export. When they need to be used elsewhere, just introduce the module global.

Modules that need to use global variables html5.vue

  
Copy after login

2. Mount the global variable module into Vue.prototype.

Same as above for Global.js, add the following code to main.js at the program entrance

import global_ from './components/tool/Global' Vue.prototype.GLOBAL = global_
Copy after login

After mounting, in the module that needs to reference the global variable, there is no need to Import the global module and reference it directly using this, as follows:

Copy after login

3. Use VUEX

Vuex is a tool specially designed for Vue State management patterns for .js application development. It uses centralized storage to manage the state of all components of the application. Therefore, global variables can be stored. Because Vuex is a bit cumbersome, it feels like overkill. I don't think it's necessary.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Vue’s routing dynamic redirection and navigation guard examples

JS implements adding event operations for dynamically created elements Example

Introduction to the calling sequence of functions in vue

The above is the detailed content of How to set global variables in vue2? (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!