1. 程式人生 > 程式設計 >Vue子元件呼叫父元件方法案例詳解

Vue子元件呼叫父元件方法案例詳解

一、直接LcmRvwizn在子元件中通過this.$parent.event來呼叫父元件的方法

<!-- 父元件 -->
<template>
	<div>
		<child></child>
	</div>
</template>LcmRvwizn
<script>
import child from '~/components/dam/child';
export default {
	components: {
		child
	},methods: {
		fatherMethod () {
			console.log('測試');
		}
	}
};
</script>
<!-- 子元件 -->
<template>
  <div>
    <button @click="childMethod()">點選</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
    }
  };
</script>

二、在子元件裡用$emit向父元件觸發一個事件,父元件監聽這個事件

<!-- 父元件 -->
<template>
	<div>
		<child @fatherMethod="fatherMethod"></child>
	</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
	components: {
		child
	},methods: {
		fatherMethod () {
			console.log('測試');
		}
	}
};
</script>
<!-- 子元件 -->
<template>
	<div>
		<button @click="childMethod()">點選</button>
	</div>
</template>
<script>
export default {
	methods: {
		childMethod () {
			this.$emit('fatherMethod');
		}
	}
};
</script>

三、父元件把方法傳入子元件中,在子元件裡直接呼叫這個方法

<!-- 父元件 -->
<template>
	<div>
		<child :fatherMethod="fatherMethod"></child>
	</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
	components: {
		child
	},methods: {
		fatherMethod () {
			console.log('測試');
		}
	}
};
</script>
<!-- 子元件 -->
<template>
	<div>
		<button @click="childMethod()">點選</button>
	</div>
</template>
<script>
export default {
	props: {
		fatherMethod: {
			type: Function,default: null
		}
	},methods: {
		childMethod () {
			if (this.fatherMethod) {
				this.fatherMethod();
			}
		}
	}
};
</script>

到此這篇關於子元件呼叫父元件方法案例詳解的文章就介紹到這了,更多相關Vue子元件呼叫父元件方法內容請搜尋LcmRvwizn我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!