vue父组件使用子组件函数,vue子组件使用父组件函数
生活随笔
收集整理的這篇文章主要介紹了
vue父组件使用子组件函数,vue子组件使用父组件函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
(1)vue中父組件調用子組件函數
用法: 子組件上定義ref="refName", 父組件的方法中用 this.$refs.refName.method 去調用子組件方法
詳解: 父組件里面調用子組件的函數,父組件先把函數/方法以屬性形式傳給子組件;那么就需要先找到子組件對象 ,即 this.$refs.refName.
然后再進行調用,也就是 this.$refs.refName.method
子組件:
<template><div>childComponent</div></template><script>export default {name: "child",methods: {childClick(e) {console.log(e)}}}</script>父組件:
<template><div><button @click="parentClick">點擊</button><Child ref="mychild" /> //使用組件標簽</div></template><script>import Child from './child'; //引入子組件Childexport default {name: "parent",components: {Child // 將組件隱射為標簽},methods: {parentClick() {this.$refs.mychild.childClick("我是子組件里面的方法哦"); // 調用子組件的方法childClick}}}</script>(2)vue中子組件調用父組件函數
方法一:
第一種方法是直接在子組件中通過this.$parent.event來調用父組件的方法
父組件:
<template><div><child></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.$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父组件使用子组件函数,vue子组件使用父组件函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美篇app如何分享到微信
- 下一篇: vue将原生事件绑定到组件