vue项目中父组件调用子组件的方法

本文介绍了在Vue项目中,父组件如何调用子组件的方法。方法一是通过`ref`属性直接调用,例如在父组件的`handleClick`方法中调用`this.$refs.child.resetFields()`;方法二是利用`$emit`和`$on`,子组件在`mounted`钩子中注册`$on`监听,并在父组件中通过`$emit`触发。这两种方式都是Vue中实现父子组件通信的常见实践。
摘要由CSDN通过智能技术生成

vue项目中父组件调用子组件的方法:

方法一:通过ref直接调用子组件的方法

//父组件中
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/>
    </div>
</template>    
<script>
import Child from './child';
export default {
    methods: {
        handleClick() {
              this.$refs.child.resetFields();
        },
    },
}
</script>
//子组件中
<template>
  <div>我是子组件</div>
</template>
<script>
export default {
  methods: {
    resetFields() {
      console.log('我是子组件的方法');
    },
  },
};
</script>

方案二:通过组件的 e m i t 、 emit、 emiton方法;

//父组件中
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/>
    </div>
</template>    

<script>
import Child from './child';
export default {
  methods: {
    handleClick() {
       this.$refs.child.$emit("childmethod") //子组件$on中的名字
    },
  },
}
</script>
//子组件中
<template>
    <div>我是子组件</div>
</template>
<script>
export default {
    mounted() {
        this.$nextTick(function() {
            this.$on('childmethods', function() {
                console.log('我是子组件方法');
            });
        });
     },
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值