vue 子组件触发父组件方法的两种方式

本文详细介绍了在Vue.js中实现子组件与父组件通信的两种常见方法:通过$emit触发事件和利用props传递函数。第一种方法使用$emit触发父组件的watchChild事件,父组件监听该事件并调用parentReceive方法进行响应。第二种方法则是在子组件的props中定义一个函数类型的onOK属性,父组件将方法名传递给子组件,子组件在适当时候调用该方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方法:

如下:通过this.emit()来触发父组件的方法。具体就是子组件触发emit()来触发父组件的方法。具体就是子组件触发emit()emit绑定的事件watchChild,然后父组件监听watchChild,一旦watchChild被触发便会触发父组件的parentReceive方法。
父组件:

<template>
<div>
<div @click="openChild">弹弹弹,弹出子组件</div>
<childs ref="alert" @watchChild="parentReceive"></childs> <!--监听子组件绑定的方法-->
</div>
</template>
 
<script>
import childs from '../components/modal/Alert'
export default{
	data(){
		return {
			msg: '我是父组件的msg!!!'
		}
	},
	components:{
		childs
	},
	methods:{
		parentReceive(message){
			alert(message);
		},
		openChild(){
			this.$refs.alert.open('我是子组件','子组件内容!!!!!');
		}
	}
}
</script>
 
<style>
</style>

子组件:

<template>
  <modal :show='show' ref="modal">
    <div slot="title">{{title}}</div>
    <div slot="content">{{content}}</div>
    <div slot="buttons" class="modal-buttons">
      <span class="modal-button" @click="_onClick()">确定</span>
    </div>
  </modal>
</template>
 
<script>
import Modal from './Modal'
 
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    okText: {
      type: String,
      default: '确定'
    },
  },
  data(){
  	return {
  		title: '',
  		content: ''
  	}
  },
  components: {
    Modal
  },
  methods: {
    open (title, content) {
    	this.title = title
    	this.content = content
      this.$refs.modal.open()
    },
    close () {
    	this.title = ''
    	this.content = ''    	
      this.$refs.modal.close()
    },
		_onClick(){
			this.close();
			this.$emit('watchChild','我是从子组件传过来的内容!!!');    //触发$emit绑定的watchChild方法
		}
  }
}
</script>

第二种方法:

在子组件props中定义属性onOK,类型为function,然后在父组件中把要触发的方法名传递给onOK属性,最后在子组件中判断onOk是否存在,是的话直接执行这个方法。
父组件:

<template>
<div>
<div @click="openChild">弹弹弹,弹出子组件</div>
<childs ref="alert" :on-ok="parentReceive"></childs>  <!--把父组件的方法名传给子组件的onOK属性-->
</div>
</template>
 
<script>
import childs from '../components/modal/Alert'
export default{
	data(){
		return {
			msg: '我是父组件的msg!!!'
		}
	},
	components:{
		childs
	},
	methods:{
		parentReceive(message){
			alert(message);
		},
		openChild(){
			this.$refs.alert.open('我是子组件','子组件内容!!!!!');
		}
	}
}
</script>
 
<style>
</style>

子组件:

<template>
  <modal :show='show' ref="modal">
    <div slot="title">{{title}}</div>
    <div slot="content">{{content}}</div>
    <div slot="buttons" class="modal-buttons">
      <span class="modal-button" @click="_onClick()">确定</span>
    </div>
  </modal>
</template>
 
<script>
import Modal from './Modal'
 
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    okText: {
      type: String,
      default: '确定'
    },
    onOk: {    //定义onOK属性
      type: Function
    }
  },
  data(){
  	return {
  		title: '',
  		content: ''
  	}
  },
  components: {
    Modal
  },
  methods: {
    open (title, content) {
    	this.title = title
    	this.content = content
      this.$refs.modal.open()
    },
    close () {
    	this.title = ''
    	this.content = ''    	
      this.$refs.modal.close()
    },
		_onClick(){
			this.close();
			if(this.onOk){
				this.onOk('我是子组件传递过来的数据!!!!');
			}
		}
  }
}
</script>
Vue 框架中,父组件可以通过以下几种方式触发子组件方法: ### 1. 使用 `ref` 调用子组件方法 Vue 提供了 `ref` 属性,允许父组件直接访问子组件的实例。通过 `ref`,父组件可以直接调用子组件上定义的方法。 **示例:** ```vue <!-- 子组件 --> <template> <div> <p>我是子组件</p> </div> </template> <script> export default { methods: { childMethod() { console.log('子组件方法被调用了'); }, }, }; </script> ``` ```vue <!-- 父组件 --> <template> <div> <button @click="callChildMethod">触发子组件方法</button> <ChildComponent ref="childRef" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { callChildMethod() { this.$refs.childRef.childMethod(); // 直接调用子组件方法 }, }, }; </script> ``` 这种方式简单直观,适用于需要直接操作子组件的情况[^1]。 --- ### 2. 使用 `$emit` 和事件监听 虽然 `$emit` 主要用于子组件父组件通信,但也可以通过组合使用 `$emit` 和自定义事件来实现父组件间接触发子组件方法。 **示例:** ```vue <!-- 子组件 --> <template> <div> <p>我是子组件</p> </div> </template> <script> export default { props: ['trigger'], watch: { trigger(newVal) { if (newVal) { this.childMethod(); } }, }, methods: { childMethod() { console.log('子组件方法被调用了'); }, }, }; </script> ``` ```vue <!-- 父组件 --> <template> <div> <button @click="triggerChild">触发子组件方法</button> <ChildComponent :trigger="shouldTrigger" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { shouldTrigger: false, }; }, methods: { triggerChild() { this.shouldTrigger = true; }, }, }; </script> ``` 这种方式适合在数据驱动的情况下触发子组件方法。 --- ### 3. 使用 Vuex 或全局状态管理 当多个组件之间需要共享状态或方法时,可以使用 Vuex 进行状态管理。父组件子组件都可以监听同一个状态变化,并在状态更新时执行相应的方法。 **示例:** ```javascript // store.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { triggerChildMethod: false, }, mutations: { setTrigger(state, value) { state.triggerChildMethod = value; }, }, }); ``` ```vue <!-- 子组件 --> <template> <div> <p>我是子组件</p> </div> </template> <script> export default { computed: { trigger() { return this.$store.state.triggerChildMethod; }, }, watch: { trigger(newVal) { if (newVal) { this.childMethod(); } }, }, methods: { childMethod() { console.log('子组件方法被调用了'); }, }, }; </script> ``` ```vue <!-- 父组件 --> <template> <div> <button @click="triggerChild">触发子组件方法</button> </div> </template> <script> export default { methods: { triggerChild() { this.$store.commit('setTrigger', true); }, }, }; </script> ``` 这种方式适用于复杂的项目结构,尤其是需要跨层级组件通信的情况[^3]。 --- ### 4. 使用事件总线(Event Bus) 事件总线是一种轻量级的通信方式,可以在任意两个组件之间传递消息。 **示例:** ```javascript // event-bus.js import Vue from 'vue'; export const EventBus = new Vue(); ``` ```vue <!-- 子组件 --> <template> <div> <p>我是子组件</p> </div> </template> <script> import { EventBus } from './event-bus.js'; export default { created() { EventBus.$on('trigger-child-method', () => { this.childMethod(); }); }, methods: { childMethod() { console.log('子组件方法被调用了'); }, }, }; </script> ``` ```vue <!-- 父组件 --> <template> <div> <button @click="triggerChild">触发子组件方法</button> </div> </template> <script> import { EventBus } from './event-bus.js'; export default { methods: { triggerChild() { EventBus.$emit('trigger-child-method'); }, }, }; </script> ``` 这种方式适用于不需要复杂状态管理的小型项目。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值