Vue父子组件之间属性访问

本文介绍了Vue中父子组件之间的属性访问方法,包括父组件如何通过this.$children和this.$refs访问子组件属性,以及子组件如何利用this.$parent和this.$root访问父组件和根组件的属性。详细阐述了$children和$refs的区别,以及使用注意事项。
摘要由CSDN通过智能技术生成
一.父子组件之间属性访问

通常父子组件是可以进行属性访问的,例如父组件调用子组件中的方法,变量等,这些都是可以通过拿到各自对应的父子组件对象,然后调用其属性,例如:
父组件访问子组件中的属性有两种方式

  1. 在父组件中使用this.$children拿到所有的子组件数组对象,然后索引访问对应子组件中的方法,变量等属性
  2. 通过this.$refs(子组件名称来访问),这种相比于第一种就是可以通过子组件的具体名称来访问了,避免索引顺序改变问题
1.1 父组件访问子组件(this.$children,this.$refs)

1.$children获取子组件对象列表

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>父子组件访问</title>
        <script src="./vue.js"></script>
        <style>
            [v-cloak] {
    
                display: none;
            }
        </style>
    </head>
    <body>
        <div id="app" v-cloak>
            <component1></component1>
            <button @click="btnclick">按钮</button>
        </div>

        <template id="content">
            <div>
                <span>子组件中的内容</span>
            </div>
        </template>
    
        <script>
            const vm = new Vue({
    
                el:"#app",
                data:{
    

                },
                methods:{
    
                    btnclick(){
    
                        console.log(this.$children); // this.$children返回的数所有子组件对象的数组
                        this.$children[0].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值