如何使用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定义组件之------父组件调用子组件数据

相关推荐
卷无止境14 分钟前
ECharts:把数据变成故事的可视化利器
前端
Eric_见嘉21 分钟前
在职前端 Skill 和 MCP 分享
前端·后端·agent
liangshanbo121539 分钟前
面试题:如何优化 Webpack 的打包速度?
前端·webpack·node.js
wengad1 小时前
从 wangEditor 迁到 wangEditor-next
前端·javascript·vue.js
行者-全栈开发2 小时前
【前端/JS框架】CVE-2026-3854:GitHub Enterprise Server X-Stat注入XSS漏洞深度剖析与紧急修复指南
前端·javascript·github
计算机魔术师3 小时前
AMD砸82亿买下李飞飞,这次不卖芯片卖什么?
前端
hzxpaipai3 小时前
杭州企业官网怎么建设?从策划到上线的5步建站方法
运维·服务器·前端·网络
怕浪猫4 小时前
2026年金九银十,我面了22个前端
前端·javascript·面试
IT_陈寒4 小时前
Vue 这个响应式陷阱,我的头发都掉没了
前端·人工智能·后端
FYKJ_20104 小时前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django