子组件调用父组件的方法:
父组件:
<editUser ref="editUser" v-on:childMethod="parentMethod"></editUser> <script> import editUser from './Edit.vue'; export default { data() { return { } }, methods:{ parentMethod(param){ console.log('parent'); }, } } </script>
子组件:
<script> export default { data() { return { } }, methods:{ callMethod(){ _this.$emit('childMethod','childParam'); //第一个参数名为调用的方法名,第二个参数为需要传递的参数 } } } </script>
父组件调用子组件的方法:
parent.vue
<template> <div> <h1>我是父组件</h1> <child ref="child"></child> </div> </template> <script> import child from './child' export default{ components:{ child }, methods:{ parent(){ this.$refs.child.childFn() } } } </script>
child.vue
<template> <div> <h2>我是子组件</h2> </div> </template> <script> import child from './child' export default{ components:{ child }, methods:{ childFn(){ alert('父组件调用了我') } } } </script>
关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。