Vue 父組件調用子組件的方法

1.在調用的子組件上定義一個ref屬性

   eg:ref="childItem"

2.在子組件的methods中聲明一個函數。

   eg: userInfo:function(str){console.log(str);}

3.在父組件中聲明一個函數test,並通過

this.$ref.childItem.userInfo 來使用組件中聲明的函數

父組件

<template>
    <div>
        <child ref="childItem"></child>
        <button @click='test'></button>
    </div>
</template>
<script>
import child form "./component/child"
export default {
    methods:{
        test(){
            this.$ref.childItem.userInfo('調用子組件中的方法');
        }
    }
}
</script>

子組件

<template>
    <div>
        <button @click='userInfo'></button>
    </div>
</template>
<script>
export default {
    methods:{
        userInfo(str){
           console.info(str);
        }
    }
}
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章