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>

效果如下

相关推荐
剪刀石头布啊3 小时前
vue-react为何要虚拟dom
前端
剪刀石头布啊3 小时前
ahooks常用的一些库,我们使用一下
前端
剪刀石头布啊3 小时前
从git更新本地提交记录到更新已经推送到远端记录
前端
云浪4 小时前
Go 并发实战:从零实现一个高并发安全的任务调度器
javascript·后端·go
Flynt5 小时前
axios 被投毒半年后,我把 npm 的"安全防线"实测了一遍:最信任的 SHA512 是安慰剂
前端·npm·node.js
excel6 小时前
Base62 和 Base64 有什么区别?
前端
风骏时光牛马7 小时前
大模型底层架构与AI源码深度剖析
前端
掘金挖土8 小时前
前端手摸手跑路之 AI 应用开发(九)
前端·后端
中文呀10 小时前
三维 GIS 离线缓存实战:逆向 CesiumOfflineCache,并亲手为它补上"自动更新"能力
前端