使用Vue.config.optionMergeStrategies 添加指定vue对象方法的拦截器

本文探讨了Vue中使用mixins进行方法装饰的实践。通过修改Vue.config.optionMergeStrategies,实现了mixin方法在组件方法前执行的效果。代码示例展示了如何在App.vue和mixin.js中定义同名方法,并在App组件创建时调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一次以为,刚开始想用这个实现装饰器的类似的想法,不知道怎么就街道这了.欢迎批判

我的思路是这样的: 

现在有三个文件, a.vue  mixin.js  main.js  

a 混入 mixin.js,  mixin.js 和 a.vue 中有同名方法 newMethod <Function>

那么在a中调用 newMethod方法的时候,会先执行mixin.js的同名方法;

上代码理解好点:

 

main.js

import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import store from './store'


//开始设置
Vue.config.optionMergeStrategies.methods = function (parent, child) {
    // child    是 .vue对象的methods对象
    // parent   是mixin的mihods对象


    if (!parent) { //如果没有就返回child的mihods对象
        return child
    }

    if (!child) {   //反之
        return parent
    }

    for (let parentKey in parent) { //只要minxi.js中有和组件同名的方法,我就认为他是需要设置之前执行的
        if (parentKey in child) {
            let fun = child[parentKey]
            child[parentKey] = function (...arg) {   //es6 知识 解构      
                console.log(`执行main.js  arg:${arg}`)       
                return parent[parentKey](fun, arg)
            }
        }

        return Object.assign(child)
    }
}

new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App),
    create() {
    }
})

对Vue.config.optionMergeStrategies 不了解的看我这个文章  => 只接代码

 

mixin

export default { //这里兼用使用这种模式,用module.exports 下面的解构会报错.有时间 的可以研究一下
    methods: {
        testDecoration(fun, arg) {

            console.log('执行mixin.js 的同名方法')
            try {
             console.log(`即将执行 app.vue中的同名方法 arg${arg}`)
                fun(...arg)
            } catch (e) {
                console.log('处理异常')
            }
        },
    }
}

 

App.vue

<template>
    <div id="app" style="height: 100%;width: 100%;overflow-y: hidden">
        <!--路由展示-->
        <router-view/>
    </div>
</template>

<script>
    import mixin from './mixin.js'  //引入mixin.js  

    export default {
        data:=>({
        }),
       
        methods: { 
            testDecoration(x,y){  //和 mixin.js同名方法
                console.log('这是app的方法',x,y);
            }       
        },
        created() {
           this.testDecoration(1,1000)
        },
        mixins: [mixin],//配置mixins
    }
</script>

<style lang="scss" scoped>

</style>

结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值