Home > Article > Web Front-end > How to define and use global variables and global functions in Vue? (with code)
The content of this article is about how to define and use global variables and global functions in vue? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Define variables and use them globally
Principle:
1. Create a new global variable module file separately, define some initial states of variables in the module, and use export default to expose them.
2. Introduce it in main.js and mount it to the vue instance through Vue.prototype. For use by other module files;
3. Or directly introduce it into the required module file for use;
Project directory
Step 1. Create a new global_variable .js
file, used to store variables, the example is as follows:
const baseURL = 'www.baidu.com'const token = '123456'const userSite = '林花落了春红,太匆匆'export default { baseURL, token, userSite }
Method 1: Use it in the module file that needs to be used (local reference), The example is as follows
##Method 2: Use globally, the example is as follows:
global_variable.js file into the main.js file, and use Vue.prototype to hang it on the vue instance. The example is as follows:
this), the example is as follows:
Principle:
Create a new module file, and then mount the function to the Vue instance through Vue.prototype in main.js, and output it through this. function name to run the function.Method 1. Write the function directly in main.js
Simple functions can be written directly in main.js. The example is as follows:Method 2. Create a new module file and mount it on main.js
The project directory is as follows
##1 ,
The code example in the file is as follows: <pre class="brush:js;toolbar:false;">// param为传入参数
function packageFunc (param) {
alert(param)
}
export default { // Vue.js的插件应当有一个公开方法 install。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象。
install: function (Vue) {
Vue.prototype.global_func = (param) => packageFunc(param)
}
}</pre>
2. The code example in the
file is as follows:
3. Use the function name
this in the module file that needs to be called, and call it. The code example is as follows:
Related recommendations:
##vue-cli writes vue plug-in example
The above is the detailed content of How to define and use global variables and global functions in Vue? (with code). For more information, please follow other related articles on the PHP Chinese website!