Vue 在父(子)組件引用其子(父)組件方法和屬性


Vue 在父()組件引用其子()組件方法和屬性

 

by:授客 QQ1033553122

 

開發環境

 

Win 10

element-ui  "2.8.2"

Vue 2.9.6

 

 

 

父組件代碼

<template>

    <div>

        <button @click="callChildMethod()">父組件調用子組件方法</button>

        <button @click="getChildAttribute()">父組件獲取子組件屬性</button>

 

        <header-part ref="headerChild"></header-part>

    </div>

</template>

 

<script>

import HeaderPart from "./HeaderPart";

 

 

export default {

    components: {

        HeaderPart

    },

    data() {

        return {

            title: "父組件"

        };

    },

 

    methods: {

        callChildMethod() {

            console.log("父組件中調用子組件printName方法");

            this.$refs.headerChild.printName();

        },

        getChildAttribute() {

            console.log(

                "父組件獲取子組件title屬性值:" + this.$refs.headerChild.title

            );

        },

        printName() {

            console.log("打印父組件title屬性值:" + this.title);

        }

    },

    mounted() {

        this.$customUtils.headerMenu.initMenuComponent();

    }

};

</script>

 

子組件代碼

<template>

    <div>

       

        <button @click="callFatherMethod()">子組件中調用父組件的方法</button>

        <button @click="getFatherAttribute()">子組件中獲取父組件的屬性</button>

    </div>

</template>

 

<script>

 

export default {

    data() {

        return {

            title: "子組件"

        };

    },

 

    methods: {

        callFatherMethod() {

            console.log("子組件中調用父組件printName方法")

            this.$parent.printName();

        },

        getFatherAttribute(){

            console.log("子組件獲取父組件title屬性值:" +  this.$parent.title);

 

        },

        printName(){

            console.log("打印子組件title屬性值:" + this.title)

        }

    }

  

};

</script>



實驗結果:

 

 

 

 

總結

父組件獲取中引用子組件方法、屬性

給子組件定義一個ref(假設名稱為childRef),然后父組件中通過this.$refs.childRef獲取子組件,進而引用子組件方法、屬性,如下:

this.$refs.childRef.方法(參數列表

this.$refs.childRef.屬性

 

 

子組件中獲取父組件的方法、屬性

在子組件里面通過this.$parent獲取父組件,進而引用父組件的方法和屬性,如下:

this.$parent.屬性

this.$parent.方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM