美文网首页
父组件调用子组件中的方法(Vue2)

父组件调用子组件中的方法(Vue2)

作者: QYCD | 来源:发表于2023-05-11 10:42 被阅读0次

Vue官网
仅仅是个人学习的记录

  1. 通过ref直接调用子组件的方法

这里子组件中定义一个方法sayHi:

<template>
  <div>我是子组件</div>
</template>

<script>
export default {
  name: "ChildModule",
  methods: {
    sayHi() {
      this.$toast({message: 'Hi'})
    },
  }
}
</script>

<style scoped lang="less">

</style>

父组件:

<template>
  <div class="layout">
    <child-module ref="child"></child-module>
    <van-button
      type="primary"
      @click="callChildSayHi">
      调用子组件中的sayHi方法
    </van-button>
  </div>
</template>

<script>
import ChildModule from "../../components/child-module";

export default {
  name: "CurtisTest",
  components: {
    ChildModule
  },
  data() {
    return {

    }
  },
  methods: {
    callChildSayHi() {
      this.$refs.child.sayHi();
    },
  }
}
</script>

<style scoped lang="less">
.layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 16px;
  padding: 16px;
}
</style>

总结:
1> 子组件中定义方法
2> 父组件引用并使用子组件,给子组件设置属性ref值
3> this.$refs.ref名.子组件的方法名

  1. 通过组件的emit、on方法

子组件:

<template>
  <div>我是子组件</div>
</template>

<script>
export default {
  name: "ChildModule",
  mounted() {
    this.$nextTick(function () {
      this.$on('sayHi', function () {
        this.$toast({message: 'Hi'})
      })
    })
  }
}
</script>

<style scoped lang="less">

</style>

父组件:

<template>
  <div class="layout">
    <child-module ref="child"></child-module>
    <van-button
      type="primary"
      @click="callChildSayHi">
      调用子组件中的sayHi方法
    </van-button>
  </div>
</template>

<script>
import ChildModule from "../../components/child-module";

export default {
  name: "CurtisTest",
  components: {
    ChildModule
  },
  data() {
    return {

    }
  },
  methods: {
    callChildSayHi() {
      this.$refs.child.$emit("sayHi"); // 子组件$on中的名字
    },
  }
}
</script>

<style scoped lang="less">
.layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 16px;
  padding: 16px;
}
</style>

===>> 使用第一种方法即可

相关文章

网友评论

      本文标题:父组件调用子组件中的方法(Vue2)

      本文链接:https://www.haomeiwen.com/subject/qqdjsdtx.html