通过组件内的 @ 传递方法名称,可以实现孙组件调用父组件。
代码如下:
index.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
<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
<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
<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>
效果如下