Vue子組件調用父組件事件的3種方法實例
更新時間:2024年01月11日 11:43:09 作者:嗯哼姐
大家在做vue開發(fā)過程中經常遇到父組件需要調用子組件方法或者子組件需要調用父組件的方法的情況,這篇文章主要給大家介紹了關于Vue子組件調用父組件事件的3種方法,需要的朋友可以參考下
1. 在子組件中通過this.$parent.event來調用父組件的方法,data參數(shù)可選
<template>
<div>
<h1>我是父組件</h1>
<child />
</div>
</template>
<script>
import child from '@/components/child';
export default {
components: {
child
},
methods: {
fatherMethod(data) {
console.log('我是父組件方法');
}
}
};
</script><template>
<div>
<h1>我是子組件</h1>
<button @click="childMethod(data)">點擊</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod(data);
console.log('調用父組件方法')
}
}
};
</script>2.父組件使用v-bind綁定一個變量(v-bind:變量名="值"),子組件用props接收(與created同級)
<template>
<div>
這是父組件
<child :parentHandler="parentHandler" />
</div>
</template>
<script>
import child from "@/components/child";
export default {
components: { child },
data() {
return {};
},
methods: {
parentHandler() {
console.log("這是父組件的方法");
},
},
};
</script><template>
<div>
這是子組件
<button @click="handler">這是子組件的按鈕</button>
</div>
</template>
<script>
export default {
props: {
parentHandler: {
type: Function,
default: () => {
return Function;
},
},
//parentHandler: {
// type: Object,
// default: () => {
// return {}
// },
//},
// parentHandler: {
// type: Boolean,
// default: true,
// },
// parentHandler: {
// type: Array,
// default: () => {
// return []
// },
// },
// parentHandler: {
// type: String,
// default: '',
// },
},
methods: {
handler() {
this.parentHandler();
},
},
};
</script>3.使用$refs傳值
<template>
<div>
<h3>這是父組件</h3>
<button @click="setChildInfo">向子組件傳值</button>
<h3>這是父組件中引用的子組件</h3>
<child ref="child"></child>
</div>
</template>
<script>
//子組件地址(僅供參考),具體以實際項目目錄地址為準
import child from "./Child.vue";
export default {
components: {
child: child
},
data() {
return {};
},
methods: {
// 向子組件傳值
setChildInfo() {
this.$refs.child.cInfo = "c2";
//this.$refs.child.open("c2");
}
}
};
</script>
<template>
<div>
<p>收到父組件數(shù)據(jù):{{ cInfo }}</p>
</div>
</template>
<script>
export default {
data() {
return {
cInfo: "c1"
};
},
methods: {
//open(data) {
// console.log(data);
//},
},
};
</script>總結
到此這篇關于Vue子組件調用父組件事件的3種方法的文章就介紹到這了,更多相關Vue子組件調用父組件事件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于iview和elementUI組件樣式覆蓋無效問題及解決
這篇文章主要介紹了關于iview和elementUI組件樣式覆蓋無效問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

