vue隐秘用法 (一)---- 父组件获取子组件的方法

已经很久没有写博客了,这两天又学习了几招

组件化是VUE最大的一个特点,但是有个东西竟然一点都不知道,那就太lipu了,下面就看一下吧

父组件获取子组件的方法

法一

父组件中

<template>
  <div class="father">
    <div class="father_box" @click="getSon">This is Father</div>
    <son ref="son"></son>
  </div>
</template>

<script>
import son from "@/components/son";
export default {
  components: {
    son,
  },
  methods: {
    getSon() {
      this.$refs.son.getFather();
    },
  },
};
</script>

子组件中

<template>
  <div class="son">
    <div class="son_box">This is son</div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {};
  },
  created() {},
  methods: {
    getFather() {
      console.log("触发了子组件的家");
    },
  },
};
</script>

效果
在这里插入图片描述

法二:

父组件

<template>
  <div class="father">
    <div class="father_box" @click="getSon">This is Father</div>
    <son ref="son"></son>
  </div>
</template>

<script>
import son from "@/components/son";
export default {
  components: {
    son,
  },
  methods: {
    getSon() {
      this.$refs.son.$emit("getSON")
    },
  },
};
</script>

子组件

<template>
  <div class="son">
    <div class="son_box">This is son</div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {};
  },
  mounted() {
    this.$nextTick(function () {
      this.$on("getSON", function () {
        console.log("我是子组件方法");
      });
    });
  },
  methods: {},
};
</script>

效果:
在这里插入图片描述

赶快去试试吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值