Vue边界处理【子访问父、夫访问子】

234 阅读1分钟

父访问子

children

不推荐使用,因为如果组件数量过多或者发生变动会导致源码混乱,不易操作

    <div id="app">
        <div>
            <cpns></cpns>
            <cpns></cpns>
            <cpns></cpns>
        </div>
    </div>
    
    <template>
        <div id="cpn">
            <h2>文字</h2>
        </div>
    </template>
    
    <script>
        const app = new Vue({
            el:'#app',
            data:{},
            components:{
                cpns:{
                    template:"#cpn",
                    data(){
                        name:'我是子组件的name'
                    }
                }
            },
            mounted:{
                console.log(this.$children)    //此处会打印出所有的子组件Vuecomponent对象,以数组形式展现,需要操作那个子组件使用下标取值;
                console.log(this.$children[0].name)   //取值第一个子组件中的name变量
            }
        })
    </script>

refs

推荐使用,使用ref进行区分

    <div id="app">
        <div>
            <cpns ref="aaa"></cpns>
            <cpns ref="bbb"></cpns>
            <cpns ref="ccc"></cpns>
        </div>
    </div>
    
    <template>
        <div id="cpn">
            <h2>文字</h2>
        </div>
    </template>
    
    <script>
        const app = new Vue({
            el:'#app',
            data:{},
            components:{
                cpns:{
                    template:"#cpn",
                    data(){
                        name:'我是子组件的name'
                    }
                }
            },
            mounted:{
                console.log(this.$refs)    //此处会打印出所有的子组件Vuecomponent对象,以对象形式展现;
                console.log(this.$refs.aaa.name)   //取值第一个子组件中的name变量
            }
        })
    </script>

子访问父

parent

    <div id="app">
        <div>
            <cpns ref="aaa"></cpns>
            <cpns ref="bbb"></cpns>
            <cpns ref="ccc"></cpns>
        </div>
    </div>
    
    <template>
        <div id="cpn">
            <h2>文字</h2>
        </div>
    </template>
    
    <script>
        const app = new Vue({
            el:'#app',
            data:{},
            components:{
                cpns:{
                    template:"#cpn",
                    data(){
                        name:'我是子组件的name'
                    },
                    mounted:{
                        console.log(this.$parent)    //此时会打印父组件的信息
                    }
                }
            },
            
        })
    </script>

root

    <script>
        const app = new Vue({
            el:'#app',
            data:{},
            components:{
                cpns:{
                    template:"#cpn",
                    data(){
                        name:'我是子组件的name'
                    },
                    mounted:{
                        console.log(this.$root)    //此时会打印Vue实例中的信息
                    }
                }
            },
            
        })
    </script>

尽量不要在子组件中直接操作父组件以及根组件中的值,避免不必要的麻烦