Vue创建全局函数
当我们有一些很多组件可以共用(且较为通用)的函数时,可以封装为全局函数。Vue有两种常见的全局函数定义方式:
- 使用Vue.prototype创建
- 使用Vue.mixin创建
但是不建议使用太多的全局函数,可能导致代码难以维护和理解。
使用 Vue.prototype 创建全局函数
通过 Vue.prototype 将函数挂载到 Vue 实例上,在其他组件中就可以通过 this.$func() 来执行函数。
可以直接在 main.js 里面编写函数
1 2 3
| Vue.prototype.test = function() { console.log('do global func'); };
|
当然,这么写是不太优雅的,通常是将全局函数单独写到一个js文件
1 2 3 4 5 6 7 8 9 10
| exports.install = function(Vue, options) { Vue.prototype.test1 = function() { console.log('do global func test1'); }; Vue.prototype.test1 = function() { console.log('do global func test2'); }; };
|
然后在main.js中引入
1 2 3 4
| import Vue from 'vue' import base from './common.js'
Vue.use(base);
|
组件中调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
<template> <div> <button @click="callGlobalFunction">Click</button> </div> </template>
<script> export default { methods: { callGlobalFunction() { this.$test1(); this.$test2(); }, }, }; </script>
|
使用Vue.mixin创建全局函数
首先定义一个globalMixin
1 2 3 4 5 6 7 8 9
|
export default { methods: { globalFunction() { console.log('This is a global function.'); } } }
|
然后再main.js中引入
1 2 3 4 5 6 7 8 9
| import Vue from 'vue'; import App from './App.vue'; import globalMixin from './globalMixin';
Vue.mixin(globalMixin);
new Vue({ render: h => h(App), }).$mount('#app');
|
组件中调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
<template> <div> <button @click="callGlobalFunction">Click</button> </div> </template>
<script> export default { methods: { callGlobalFunction() { this.globalFunction(); }, }, }; </script>
|
二者区别
Vue.prototype
- 使用 Vue.prototype 可以将一个函数或任何类型的对象添加到 Vue 的原型上,从而使其在所有 Vue 实例中都可用。因此通过
this
关键字可以在 Vue 组件中访问这个函数或对象
- 全局函数通过 this.$functionName() 或 this.$propertyName 的方式在组件中调用
- 适合那些在组件中调用,且没有涉及组件生命周期的函数。比如常用的工具函数、格式化函数等。这样可以简化代码,避免在每个组件中重复定义这些全局函数
Vue.mixin
- Vue.mixin 允许将一个混入对象应用到所有的组件中,从而在每个组件的生命周期钩子函数中添加相同的逻辑或函数。它可以在多个组件中共享相同的代码,从而实现代码复用
- 全局函数通过 this.functionName() 或 this.propertyName 的方式在组件中调用,而不需要加上
$
符号
- 适合那些需要在多个组件中共享相同逻辑的函数,比如统一的权限控制、错误处理、样式或功能的全局应用等