这是一次以为,刚开始想用这个实现装饰器的类似的想法,不知道怎么就街道这了.欢迎批判
我的思路是这样的:
现在有三个文件, 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>
结果