首页 » 前端 » Vue.js » 正文

另类,Vue: 在父组件中调用子组件中的方法(emit)

发布者:站点默认
2022/05/24 浏览数(335) 分类:Vue.js 另类,Vue: 在父组件中调用子组件中的方法(emit)已关闭评论

不推荐使用本文的方法,建议使用 props 和 emit

方法来自:stackoverflow.com/questions/55316490,在用这个方法前可以先试试 this.$refs[‘子组件’].doSth(),比下文的方法简单。

子组件

export default {
  methods: {
    doSth() {
      console.log('子组件的 doSth 方法');
    },
  },
  mounted() {
    let self = this;
    self.$emit('callback', {
      doSth: () => self.doSth(),
    });
  },
};

父组件

<template>
  <子组件 @callback="v => $options.callbackHandle = v" />
</template>

<script>
export default {
  data() {
  },
  callbackHandle: {
    doSth: () => {},
  },
  methods: {
    // 调用子组件中的方法
    doChildMethod() {
      let self = this;
      self.$options.callbackHandle.doSth();
    },
  },
};
</script>

expose in Vue.js v3.2+

点击返回顶部
  1. 留言
  2. 联系方式