当前位置: 首页 > Web前端 > vue.js

vue是如何封装和调用公共方法的

时间:2023-04-01 11:14:12 vue.js

在业务中,我们经常会遇到同一个方法需要调用多次。这时候如果每次都写,代码不够优雅,所以封装公共方法是非常必要的第一步:封装公共方法1.在vue项目的src/assets/js/下创建一个js文件Example:common.js2.main.js中引用common->instance/*引入公共函数*/importcommonfrom'./assets/js/common'Vue.use(common);3.common.js写一个例子exportdefault{install(Vue){//这里是例子方法getTime是方法名function()可以带参数Vue.prototype.getTime=function(){vardate=newDate()vary=date.getFullYear()varm=date.getMonth()+1m=m<10?('0'+m):mvard=date.getDate()d=d<10?('0'+d):dalert(y+m+d)}}}这里我们封装了示例public方法,接下来我们如何展示callcallpublicmethod1.在任何生命周期this。vue文件中的方法名是可以的,因为created(){this.getTime()}已经在main.js中全局实例化了2.页面会调用该方法