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.方法

posted @   授客  阅读(2633)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示