vue 孙组件调用父组件的方法

通过组件内的 @ 传递方法名称,可以实现孙组件调用父组件。

代码如下:

index.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="/framework/vue-2.7.16.min.js"></script>
    <script src="/framework/httpVueLoader.min.js"></script>
    <title>孙组件调用父组件的方法</title>
</head>
<body>
    <div id="vue2x">
        <h2> 萨瓦迪卡 </h2>
        <item-m1>这里是父组件</item-m1>
    </div>
    <script>
        var vm = new Vue({
            el: '#vue2x',
            data: { val: 123 },
            components: { "item-m1": httpVueLoader('m1.vue') }
        });
    </script>
</body>
</html>

父组件 m1.vue

html 复制代码
<template>
    <div class="sr">
        <slot></slot>
        <!-- 在子组件标签中用 @ 语法糖向子组件传递方法 -->
        <item-m2 @call-parent-method="parentMethod">这里是子组件</item-m2>
    </div>
</template>

<script>
module.exports = {
    methods: {
        parentMethod() {
            console.log('父组件的方法被调用');
        }
    },
    components: { "item-m2": httpVueLoader('m2.vue') }
}
</script>
<style scoped>
.sr {
    display: flex;
    border: 1px solid #467c46;
    padding: 15px;
    margin: 15px;
}
</style>

子组件 m2.vue

html 复制代码
<template>
    <div class="sr">
        <slot></slot>
        <item-m3 @call-grandparent-method="grandparentMethod">这里是孙组件</item-m3>
    </div>
</template>

<script>
module.exports = {
    methods: {
        grandparentMethod() {
            // 触发父组件的方法
            this.$emit('call-parent-method');
        }
    },
    components: { "item-m3": httpVueLoader('m3.vue') }
}
</script>

孙组件 m3.vue

html 复制代码
<template>
    <div class="sr">
        <slot></slot>
        <button @click="callM1Method">调用父组件</button>
    </div>
</template>

<script>
module.exports = {
    methods: {
        callM1Method() {
            this.$emit('call-grandparent-method');
            console.log('显示来自父组件的参数:',vm.val);
        }
    }
}
</script>

效果如下

相关推荐
Liora_Yvonne7 小时前
为什么你写了3年前端还是搭不好一个项目
前端·架构
snow@li7 小时前
Java:后端项目会有一个类似前端node_modules的目录吗 / jar包在本地仓库 ~/.m2/repository 中按版本共存
java·开发语言·前端
weedsfly7 小时前
单例模式在前端中的正确打开方式
前端·javascript·面试
PedroQue997 小时前
uni-router新推useUniEventChannel,彻底解决页面通信难题
前端·uni-app
IT_陈寒7 小时前
Vite冷启动快?我遇到了个奇怪的依赖问题
前端·人工智能·后端
2603_955279707 小时前
通过 brew upgrade cmake 升级到最新版本
前端
卓怡学长7 小时前
w268基于springboot + vue 物流系统
java·数据库·vue.js·spring boot·spring·intellij-idea
FREEDOM_X7 小时前
Linux 进程间通讯(IPC)——总结
linux·c语言·前端·嵌入式硬件·struts
WWBQU7 小时前
前端day06
前端
岁月宁静7 小时前
DeepSeek Harness 团队 招聘 :JD反推:新手如何系统掌握AI Agent开发技术?
前端·人工智能·后端