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>

效果如下

相关推荐
Jackson__几秒前
聊聊 JS 中的可选链 ?.
前端
前端小崔6 分钟前
前端面试题之ES6保姆级教程
开发语言·前端·javascript·面试·职场和发展·ecmascript·es6
Bug从此不上门15 分钟前
【无标题】
前端·javascript·uni-app·vue
HarderCoder15 分钟前
ByAI:Redux中间件的原理和ts简化实现
前端·redux
贩卖纯净水.19 分钟前
Webpack依赖
前端·webpack·node.js
crary,记忆20 分钟前
微前端 - Module Federation使用完整示例
前端·react·angular
不知几秋26 分钟前
Spring Boot
java·前端·spring boot
程序猿ZhangSir29 分钟前
Vue3 项目的基本架构解读
前端·javascript·vue.js
HarderCoder34 分钟前
ByAI: Redux的typescript简化实现
前端
90后的晨仔41 分钟前
RxSwift 框架解析
前端·ios