一、前言
项目开发过程中,定义的方法、变量、组件如果被多处引用,就要考虑将其抽取为公共部分,提升代码复用度,便于维护。
二、全局变量挂载
有以下两种方式可实现全局挂载全局变量。
2.1 方式一:Vue.prototype
1、添加实例 property
你可能会在很多组件里用到数据/实用工具,但是不想污染全局作用域。这种情况下,你可以通过在原型上定义它们使其在每个 Vue 实例中可用。
Vue.prototype.$appName = 'My App'
这样 $appName 就在所有的 Vue 实例中可用了,甚至在实例被创建之前就可以。如果我们运行:
new Vue({ beforeCreate: function () { console.log(this.$appName) } })
则控制台会打印出 My App。就这么简单!
2.2 对象引入
1、新建 global_variable.js文件,用于存放变量,示例如下:
const startDate = new Date(new Date() - 24 * 60 * 60 * 1000 * 30) const endDate = new Date() const dataText = ''//表格置空 export default { startDate, endDate, dataText, }
全局使用,示例如下:
import globalVariable from './assets/js/global_variable' Vue.prototype.GLOBAL = globalVariable
在需要使用的模块文件中使用(无需引入,直接通过this使用),示例如下:
data() { return { startDate: this.GLOBAL.startDate, //开始时间 endDate: this.GLOBAL.endDate, //结束时间 dataText: this.GLOBAL.dataText, //表格开始置空 }; },
注⚠️:务必以$开头,否则会命名冲突!
三、全局挂载全局函数
有很多函数在重复使用,所以,我们可以对这些函数进行全局挂载,省时又省力!
实现过程如下:
单独新建一个全局变量模块文件,模块中定义一些变量初始状态,用export default 暴露出去;
在main.js中引入,并通过Vue.prototype挂载到vue实例上面。供其他模块文件使用;
或者直接引入到需要的模块文件中使用;
有以下两种方式可实现全局挂载全局函数。
3.1 方式一:Vue.prototype
在main.js加入
// Vue 全局挂载自定义函数 // folding为传进来的参数 // internalFolding 为函数名 Vue.prototype.internalFolding = function (folding){ //函数内容 }
在所有组件里可调用函数
this.internalFolding(folding)
这里的引用方式不推荐使用,因为所有的引用都放到main.js中会显得很乱!
3.2 方式二:exports.install + Vue.prototype
写好自己需要的公共JS文件(folding.js)
exports.install = function (Vue, options) { Vue.prototype.internalFolding = function (folding){ if(folding){ $(".abnormal-center-right").css("left","1%"); }else{ $(".abnormal-center-right").css("left","21%"); } }; };
main.js 引入并使用
import folding from '@/static/js/folding' Vue.use(folding);
所有组件里可调用函数
this.internalFolding(this.folding);
这里的引用方式推荐使用!
注:exports.install为vue的插件语法糖,方便用vue.use 使用的。
四、全局组件挂载
在main.js中全局注册到vue中。
import MyBread from '@/components/common/MyBread.vue' Vue.component("MyBread", MyBread);//全局自定义组件
在需要的组件中可以直接使用,注意需要父子传值
<MyBread level1="用户管理" level2="用户列表"></MyBread>
发表评论 取消回复