Skip to content

在子组件中调用父组件的方法

  • 子组件.vue
html
<script>
	export default {
		methods: {
      test() {
        this.$parent.test_father('NO!~');
      },
    }
}
</script>
<script>
	export default {
		methods: {
      test() {
        this.$parent.test_father('NO!~');
      },
    }
}
</script>
  • 父组件.vue
html
<script>
	export default {
		methods: {
      test_father(val) {
        console.log(val)
      },
    }
}
</script>
<script>
	export default {
		methods: {
      test_father(val) {
        console.log(val)
      },
    }
}
</script>

注意

有可能出现这种情况:在父组件引用子组件的时候,子组件中的方法的调用者是在 UI 组件中的(比如ele表格行中的按钮),导致找不到父组件。

解决方案:

  • 多写几个 .$parent 试一试;
  • 不要让子组件方法调用者放到UI组件中;

在父组件中调用子组件的方法

使用ref

  • 父组件.vue
html
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/></Child>
    </div>
</template>

<script>
import Child from './child'

export default {
    methods: {
        handleClick() {
              this.$refs.child.test_son('测试参数');
        },
    },
}
</script>
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/></Child>
    </div>
</template>

<script>
import Child from './child'

export default {
    methods: {
        handleClick() {
              this.$refs.child.test_son('测试参数');
        },
    },
}
</script>
  • 子组件.vue
js
export default {
  methods: {
    test_son(params) {
      console.log('我是子组件的方法,接收到的参数: ',params);
    },
  },
}
export default {
  methods: {
    test_son(params) {
      console.log('我是子组件的方法,接收到的参数: ',params);
    },
  },
}