如何使用vue定义组件之——父组件调用子组件

首先,我们需要创建两个组件模板template:

javascript 复制代码
    <template id="father">
        <div>
            <h3>我是父组件</h3>
            <h3>访问自己的数据:</h3>
            <h3>{{ msg }}</h3>
        </div>
    </template>

    <template id="children">
        <div>
            <h5>我是子组件</h5>
            <h5>访问自己的数据:{{ sex }}</h5>
        </div>
    </template>

创建父子关系,使用vue将子组件添加到父组件里面,并且添加一些数据以便展示:

javascript 复制代码
 new Vue({
        el: '.container',
        components: {
            'my-father': {//父组件
                template: '#father',
                data() {
                    return {
                        msg: "welcome father!",
                        name: "I'm a father!",
                        age: 66,
                        user: {
                            id: 1001,
                            username: 'admin'
                        },
                        sex: null
                    }
                },
                components: {
                    'my-children': { //子组件,只能在 my-father中调该组件
                        template: '#children',
                        data() {
                            return {
                                sex: 'male'
                            }
                        }
                    }
                }
            }
        }
    })

现在,可以调用父组件了:

javascript 复制代码
    <div class="container">
        <my-father></my-father>
        <my-father></my-father>
        <my-father>
            <!-- 此处也不能访问到子组件的数据,必须在父组件的template中引用子组件 -->
            <!-- <my-children></my-children> -->
        </my-father>
        
        <!-- 此处无法调用子组件,子组件必须依赖于父组件进行展示 -->
        <!-- <my-children></my-children> -->
    </div>

问题来了,那么如何调用子组件呢?

javascript 复制代码
    <template id="father">
        <div>
            <h3>我是父组件</h3>
            <h3>访问自己的数据:</h3>
            <h3>{{ msg }}</h3>
            <my-children></my-children><hr>
        </div>
    </template>

展示结果:

相关文章:

如何使用vue定义组件之------全局or局部

如何使用vue定义组件之------子组件调用父组件数据

如何使用vue定义组件之------父组件调用子组件数据

相关推荐
木斯佳2 小时前
前端八股文面经大全:bilibili生态技术方向二面 (2026-03-25)·面经深度解析
前端·ai·ssd·sse·rag
不会写DN2 小时前
Gin 日志体系详解
前端·javascript·gin
冬夜戏雪3 小时前
实习面经记录(十)
java·前端·javascript
爱学习的程序媛4 小时前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web
小码哥_常4 小时前
从SharedPreferences到DataStore:Android存储进化之路
前端
老黑4 小时前
开源工具 AIDA:给 AI 辅助开发加一个数据采集层,让 AI 从错误中自动学习(Glama 3A 认证)
前端·react.js·ai·nodejs·cursor·vibe coding·claude code
薛先生_0994 小时前
js学习语法第一天
开发语言·javascript·学习
jessecyj5 小时前
Spring boot整合quartz方法
java·前端·spring boot
苦瓜小生5 小时前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
天若有情6735 小时前
前端HTML精讲03:页面性能优化+懒加载,搞定首屏加速
前端·性能优化·html