一,vue的this. c h i l d r e n 和 t h i s . children和this. childrenthis.parent

this.$children中存放的是当前vue页面的所有子组件的数组集合。
每一个子组件中的数据和函数都可以被访问到。
例如:
子组件:

<template>
    <div>
        <h3>这是子组件的内容</h3>
        <button @click="change">按钮触发事件</button>
        <button @click="test">子组件直接触发父组件的事件</button>
    </div>
</template>

<script>
export default {
    methods:{
        change(){
            this.$emit("change")
        },
        test(){
            this.$parent.dosomething()
        }
    }
}
</script>

<style lang="less" scoped>

</style>

父组件:

<template>
    <div>
        <h1>父组件</h1>
        <h1>底下是子组件</h1>
        <div>{{msg}}</div>
        <child @change="change"></child>
    </div>
</template>

<script>
import child from "../views/Child"
    export default {
        data(){
            return{
                msg:"刚开始父组件中的数据"
            }
        },
        components:{
            child
        },
        methods:{
            change(){
                this.msg="修改之后父组件的数据"
            },
            dosomething(){
                console.log("在这里做一些事情,它是父组件中的事情")
            }
        },
        mounted(){
            this.$children[0].change()
        }
    }
</script>

<style lang="lsee" scoped>

</style>

在这里插入图片描述
就可以在父组件中直接调用执行子组件中的change函数。
而每个组件只有一个父组件,故而this.$parent就是父组件对象。同样的,可以在子组件中直接通过它来访问父组件中的数据,调用父组件中的函数。

二,直接使用this.$ref来定位

<child @change="change" ref="myChild"></child>
然后定位使用时,this.$refs.myChild就可以定位到这个子组件。从而进一步获取子组件的元素、数据、方法等
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐