[Vue] mixins 混入函数重载后调用原函数

可能有这么个情况:

// a.js
export default {
  ...
  methods: {
    hello() {
      console.log('hello, a')
    }
  },
  ...
}

在 b.js 中混入 a.js

// b.js
import a from 'a.js'

export default {
  ...
  mixins:[a],
  methods: {
    hello(msg) {
      console.log('hello, b', msg)
    }
  },
  ...
}

那么,怎么在 b.js 中调用 a 的 hello 方法呢? 这类似于继承时调用父类的同名函数。

解决问题:

// b.js
import a from 'a.js'

export default {
  ...
  mixins:[a],
  methods: {
    hello(msg) {
      console.log('hello, b', msg)
      this._super_hello(msg)
    },
    // 这样子写
    _super_hello(...args) {
      return a.methods['hello'].call(this, ...args)
    },
  },
  ...
}

意义

这么做有什么意义?

就说一个吧。使用上面的方法,可以用来修改一些js库或组件的行为。因为,上面的方法实际上就是一个 HOOK,没错,它和曾经的那些 API HOOK 没什么两样。安装一个钩子,干点自己的事,再调用原来的实现,就可以实现特定的功能了。

END

posted @ 2022-07-28 16:04  我爱我家喵喵  阅读(236)  评论(0编辑  收藏  举报