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

  • 相关阅读:
    剑指 Offer 53
    Visual Studio Ultimate 2013
    手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
    DirectX的Vertex Buffer顶点缓冲的理解和应用 Shader必知必会
    Qt5.2中的android环境搭建
    JavaScript的基础学习篇
    九月十月百度,迅雷,华为,阿里巴巴最新校招笔试面试三十题(10.18)
    十月下旬腾讯,网易游戏,百度迅雷校园招聘笔试题集锦(第271-330题)
    九月十月百度人搜,阿里巴巴,腾讯华为笔试面试八十题(第331-410题)
    十月上旬百度,阿里巴巴,迅雷搜狗最新面试七十题(第201-270题)
  • 原文地址:https://www.cnblogs.com/shouke/p/13170512.html
Copyright © 2020-2023  润新知