vue 把组件方法暴露到window对象中

方法 1(简单,但不推荐)

mounted() {
  // 2. 在mounted阶段声明globalFn,来调用组件内的方法
  window.globalFn = () => {
    this.getDetail()
  }
},
methods: {
  // 1. 组件内有一个getDetail方法,需要暴露给window,以供嵌入该页面的客户端调用
  getDetail() {
    // 业务逻辑
  }
}

优点:

  1. 简单: 适合暴露的方法不太多的系统

缺点:

  1. 变量名易冲突: 如果需要暴露的方法越来越多,那么 window 对象中的全局变量也会越来越多,容易变量名冲突

  2. 位置分散: 随着业务的复杂化,暴露的方法可能分散在各个.vue 文件中,不容易管理

方法 2(推荐,解决方法 1 的痛点)

  1. main.js 中把 Vue 对象暴露给 window
// ...
const vm = new Vue({
  router,
  store,
  render: (h) => h(App)
}).$mount('#app')
window.vm = vm // 只把vm暴露给window,以后都在vm中做文章
// ...
  1. 在一个你喜欢的目录下新建 js 文件,该文件用来存放需要暴露出去的方法

(我是把这个文件放在了 @/utils/export2vmFunction.js 下)

exports.install = function (Vue) {
  // 把需要暴露出去的方法挂载到Vue原型上,避免了全局变量过多的问题
  // 全局方法都在这里,方便管理
  Vue.prototype.globalFn1 = function () {
    const component = findComponentDownward(this, 'RecommendRecord1')
    component.getDetail1()
  }

  Vue.prototype.globalFn2 = function () {
    const component = findComponentDownward(this, 'RecommendRecord2')
    component.getDetail2()
  }

  // ...
}

/**
 * 由一个组件,向下找到最近的指定组件
 * @param {*} context 当前上下文,比如你要基于哪个组件来向上寻找,一般都是基于当前的组件,也就是传入 this
 * @param {*} componentName 要找的组件的 name
 */
function findComponentDownward(context, componentName) {
  const childrens = context.$children
  let children = null

  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options.name

      if (name === componentName) {
        children = child
        break
      } else {
        children = findComponentDownward(child, componentName)
        if (children) break
      }
    }
  }
  return children
}

注:如果对上述找组件的方法不熟悉的小伙伴可以移步到:找到任意组件实例的方法

  1. 把目光在回到 main.js 中,导入刚刚声明好的 js 文件
// ...
import Vue from 'vue'
import vmFunction from '@/utils/export2vmFunction'
Vue.use(vmFunction)
// ...
  1. 大功告成

经过上述三步操作后,就可以用vm.globalFn1()来调用组件内的方法了

优点:

  1. 方便管理: 所有方法都在一个文件中

  2. 全局变量少: 只有vm一个变量

  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值