vue3 父组件调用子组件方法

  1. 使用ref属性(推荐方式)
    • 步骤一:在父组件中给子组件添加ref属性
      • 在父组件的模板中,给子组件标签添加ref属性,用于获取子组件的引用。例如,有一个父组件Parent.vue和子组件Child.vue,在Parent.vue中:
      <template>
        <div>
          <h1>父组件</h1>
          <Child ref="childComponentRef"></Child>
          <button @click="callChildMethod">调用子组件方法</button>
        </div>
      </template>
      <script setup>
      import { ref } from 'vue';
      import Child from './Child.vue';
      const childComponentRef = ref(null);
      const callChildMethod = () => {
        if (childComponentRef.value) {
          // 假设子组件有一个名为childMethod的方法
          childComponentRef.value.childMethod();
        }
      };
      </script>
      
    • 步骤二:在子组件中暴露方法(使用defineExpose
      • 在子组件Child.vue中,通过defineExpose函数将希望被父组件调用的方法暴露出来。
      <template>
        <div>
          <h2>子组件</h2>
        </div>
      </template>
      <script setup>
      const childMethod = () => {
        console.log('子组件的方法被调用了');
      };
      // 将方法暴露给父组件
      defineExpose({
        childMethod
      });
      </script>
      
  2. 通过$parent访问(不推荐,耦合性强)
    • 这种方式是通过$parent属性来访问父组件。在子组件中,$parent指向父组件实例。但是这种方式会使组件之间的耦合性变强,不符合组件化的设计理念。
    • 示例:假设父组件中有一个方法parentMethod,子组件想要调用它
      • 父组件(Parent.vue
        <template>
          <div>
            <h1>父组件</h1>
            <Child></Child>
          </div>
        </template>
        <script setup>
        import Child from './Child.vue';
        const parentMethod = () => {
          console.log('父组件的方法被调用了');
        };
        </script>
        
      • 子组件(Child.vue
        <template>
          <div>
            <h2>子组件</h2>
            <button @click="callParentMethod">调用父组件方法</button>
          </div>
        </template>
        <script setup>
        const callParentMethod = () => {
          // 通过$parent访问父组件方法
          if (this.$parent && typeof this.$parent.parentMethod === 'function') {
            this.$parent.parentMethod();
          }
        };
        </script>
        
    • 不过在Vue 3中,$parent的使用可能会受到一些限制,并且这种方式破坏了组件的封装性,不建议在实际开发中大量使用。通常情况下,优先考虑使用ref来获取子组件引用并调用其方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值