父子组件的访问

父访问子

方式一:$children(不常用)

<body>
    <div id="app">
        <cpn></cpn>
        <button @click="btnClick">按钮</button>
    </div>
    <template id="cpn">
        <div>
            <h2>我是子组件</h2>
        </div>
    </template>
<script>
    let app = new Vue({
        el:'#app',
        data:{
        },
        components:{
            'cpn':{
                template:'#cpn',
                methods:{
                    showMessage(){
                        console.log("hello");
                    }
                }
            }
        },
        methods:{
            btnClick(){
                console.log(this.$children);
                this.$children[0].showMessage(); //访问第一个子组件的方法
            }
        }
    })
</script>
</body>
  • this.$children通过索引访问子组件,包含子组件各种信息
  • 缺点是若子组件数据相对位置改变,索引也要跟着改变,,位置是使用时的相对位置

方式二:$refs (reference:引用) 常用

用法: this.$refs.引用名.属性

<body>
    <div id="app">
        <!--给组件添加引用ref-->
        <cpn ref="myCpn"></cpn>  
        <button @click="btnClick">按钮</button>
    </div>

    <template id="cpn">
        <div>
            <h2>我是子组件</h2>
        </div>
    </template>
<script>
    let app = new Vue({
        el:'#app',
        data:{
        },
        components:{
            'cpn':{
                template:'#cpn',
                methods:{
                    showMessage(){
                        console.log("hello");
                    }
                },
                data(){
                    return{
                        name:'子组件1'
                    }
                }
            }
        },
        methods:{
            btnClick(){
                console.log(this.$refs.myCpn.name); //访问子组件的属性
                this.$refs.myCpn.showMessage();    // 调用子组件的方法
            }
        }
    })
</script>
</body>
posted @ 2020-11-29 20:10  至安  阅读(117)  评论(0编辑  收藏  举报