需求描述

随着开发的深入和代码的维护,为了某些功能的实现可以说是又秃了几根;接下来就说一说,通过 ref 实现父组件调用子组件的方法等。

1.父组件模板

​ 在父级模块的子组件上添加属性 ref 和 属性名 mySon (随意),调用时使用 this.$ref.(属性名).(子组件方法);

<template>
  <view class="">
    <son ref="mySon"></son>
    <button @click="fatherClick">父组件按钮</button>
  </view>
</template>
<script>
  import son from '@/components/son.vue'
  export default {
    components: {
      son
    },
    methods: {
      fatherClick() {
        this.$refs.mySon.sonClick("father call son");
      }
    }
  }
</script>

2.子组件模板

<template>
  <view class="">
    <text>子组件</text>
  </view>
</template>
<script>
  export default {
    name: 'son',
    methods: {
      sonClick(e) {
        console.log(e)
      }
    }
  }
</script>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐