vue3以插件的方式封装公共方法

vue3以插件的方式封装公共方法

首先在plugins文件下新建一个helper.js文件,

export const helper = {
   
   }
// 深拷贝
helper.clone = (origin) => {
   
   
    return JSON.parse(JSON.stringify(origin))
}
helper.formatTime = (dateTime) => {
   
   
    if (!dateTime) {
   
   
        return '0-0-0 0:0:0';
    }
    let date = new Date(dateTime);//时间戳为10位也就是秒需*1000,时间戳为13位也就是毫秒的话不需乘1000
    let Y = date
Vue 2 中封装公共方法可以通过以下几种方式实现: ### 创建公共方法文件 首先创建一个 `utils.js` 文件,在其中定义多个导出的函数,这些函数为纯函数,接收输入并返回结果,不依赖 Vue 的内部状态。示例代码如下: ```javascript // utils.js export function formatDate(date) { // 实现日期格式化逻辑 return new Intl.DateTimeFormat().format(date); } export function sumArray(arr) { // 实现数组求和逻辑 return arr.reduce((acc, val) => acc + val, 0); } ``` 在 Vue 组件中使用公共方法时,通过 `import` 语句导入公共方法,在 `methods` 选项中调用它们。示例代码如下: ```vue <template> <div> <p>Formatted Date: {{ formattedDate }}</p> <p>Sum of Array: {{ arraySum }}</p> </div> </template> <script> import { formatDate, sumArray } from &#39;./utils.js&#39;; export default { data() { return { currentDate: new Date(), array: [1, 2, 3, 4, 5] }; }, computed: { formattedDate() { return formatDate(this.currentDate); }, arraySum() { return sumArray(this.array); } } }; </script> ``` ### 创建 Vue 插件 创建一个 `plugin.js` 文件,将公共方法作为 Vue 插件导出。`install` 函数接收 Vue 实例 `Vue`,并使用 `Vue.prototype` 将公共方法挂载到 Vue 实例上。示例代码如下: ```javascript // plugin.js import { formatDate, sumArray } from &#39;./utils.js&#39;; const MyPlugin = { install(Vue) { Vue.prototype.$formatDate = formatDate; Vue.prototype.$sumArray = sumArray; } }; export default MyPlugin; ``` 在 `main.js` 中,通过 `Vue.use(MyPlugin)` 注册插件,使其在整个 Vue 应用中可用。示例代码如下: ```javascript // main.js import Vue from &#39;vue&#39;; import App from &#39;./App.vue&#39;; import MyPlugin from &#39;./plugin.js&#39;; Vue.use(MyPlugin); new Vue({ render: h => h(App) }).$mount(&#39;#app&#39;); ``` 在组件中,可以使用 `this.$formatDate` 和 `this.$sumArray` 调用这些方法,利用 Vue 的原型链机制。示例代码如下: ```vue <template> <div> <p>Formatted Date: {{ $formatDate(currentDate) }}</p> <p>Sum of Array: {{ $sumArray(array) }}</p> </div> </template> <script> export default { data() { return { currentDate: new Date(), array: [1, 2, 3, 4, 5] }; } }; </script> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值