uniapp 中父组件调用子组件方法

需求描述

随着开发的深入和代码的维护,为了某些功能的实现可以说是又秃了几根;接下来就说一说,通过 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>

你可能感兴趣的:(uniapp,H5,前端)