關(guān)于vue父組件調(diào)用子組件的方法
組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以表現(xiàn)為用 is 特性進(jìn)行了擴展的原生 HTML 元素。
所有的 Vue 組件同時也都是 Vue 的實例,所以可接受相同的選項對象 (除了一些根級特有的選項) 并提供相同的生命周期鉤子。
我們都知道通過$ref可以獲取到某個DOM,但是它也可以用來獲取子組件的實例,調(diào)用子組件的方法
例:
子組件:
<template> ? <div></div> </template> <script> ? export default { ? ? methods:{ ? ? ? childMethod(flag) { ? ? ? ? console.log(flag) ? ? ? } ? ? }, ? ? created(){ ? ? } ? } </script>
父組件: 在子組件中加上ref即可通過this.$refs.ref.method調(diào)用
<template> ? <div @click="parentMethod"> ? ? <children ref="child1"></children> ? </div> </template> <script> ? import children from 'components/children/children.vue' ? export default { ? ? ?data(){ ? ? ? return { ? ? ? ? flag: true ? ? ? } ? ? }, ? ? components: { ? ? ? ? ? ? 'children': children ? ? }, ? ? methods:{ ? ? ? parentMethod() { ? ? ? ? console.log(this.$refs.child1) //返回的是一個vue對象,所以可以直接調(diào)用其方法 ? ? ? ? this.$refs.child1.childMethod(this.flag);? ? ? ? } ? ? } ? } </script>
例子,兄弟組件間傳遞DOM數(shù)據(jù),調(diào)用函數(shù)
寫一個兄弟組件之間傳遞數(shù)據(jù),父組件調(diào)用方法的案例:
第一個子組件cartcont,發(fā)射數(shù)據(jù)
this.$emit('cartadd', event.target);
父組件接收數(shù)據(jù),并將數(shù)據(jù),通過調(diào)用另一個子組件shopcart 的方法傳遞給另一個子組件shopcart
<v-cartcont :food="food" @cartadd='_drop'></v-cartcont> <v-shopcart ref='shopcart'></v-shopcart> _drop(target){ ? ? console.log('父組件接收數(shù)據(jù)') ? ? this.$refs.shopcart.drop(target); }
shopcart子組件的方法
drop(el){ console.log('調(diào)用另一個子組件的方法') console.log(el) }
到此這篇關(guān)于關(guān)于vue父組件調(diào)用子組件的方法的文章就介紹到這了,更多相關(guān)vue 父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序地圖導(dǎo)航功能實現(xiàn)完整源代碼附效果圖(推薦)
這篇文章主要介紹了微信小程序地圖導(dǎo)航功能實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Ant Design Vue table中列超長顯示...并加提示語的實例
這篇文章主要介紹了Ant Design Vue table中列超長顯示...并加提示語的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10Vue使用axios進(jìn)行數(shù)據(jù)異步交互的方法
大家都知道在Vue里面有兩種出名的插件能夠支持發(fā)起異步數(shù)據(jù)傳輸和接口交互,分別是axios和vue-resource,同時vue更新到2.0之后,宣告不再對vue-resource更新,而是推薦的axios,今天就講一下怎么引入axios,需要的朋友可以參考下2024-01-01