Vue父组件调用子组件的方法(ref)

vue中如果父组件想调用子组件的方法,可以在子组件中加上ref,

然后通过this.$refs.ref.method调用,例如:

父组件:

<template>
  <div @click="fatherMethod">
    <child ref="child"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child.vue';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {this.$refs.child.childMethods();
      }
    }
  };
</script>


子组件:

<template>
  <div>{{name}}</div>
</template>
<script>
  export default {
    data() {
      return {
        name: '测试'
      };
    },
    methods: {
      childMethods() {
        console.log(this.name);
      }
    }
  };
</script>


在父组件中, this.$refs.child 返回的是一个vue实例,可以直接调用这个实例的方法
 

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue中,如果组件想要调用组件方法,可以通过使用ref属性来实现。首先,在组件标签上加上ref属性,比如ref="child"。然后就可以在组件中使用this.$refs.child来获取组件实例,然后调用组件方法,比如this.$refs.child.childMethods()。这样就可以在组件中通过ref调用组件方法了。 另外,还可以通过在组件中使用@click等事件绑定来调用组件方法。首先,在组件中引入组件,并将组件注册为组件的一个组件。然后可以在组件的methods选项中定义一个方法,比如fatherMethod,在该方法中通过this.$refs.child.childMethod()来调用组件方法。最后,在组件的模板中通过@click等事件绑定调用fatherMethod方法,从而触发组件方法调用。 综上所述,可以通过ref属性或事件绑定来实现在Vue组件调用组件方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue 组件调用组件方法ref](https://blog.csdn.net/coinisi_li/article/details/127117626)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [vue 组件调用组件方法](https://blog.csdn.net/qq_29236119/article/details/113558032)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值