PHP前端开发

vue怎么调用组件方法

百变鹏仔 3周前 (09-25) #VUE
文章标签 组件
在 vue 中调用组件方法的方法有三种:直接调用、通过事件触发和通过 provide/inject 机制。直接调用使用 $refs 对象,通过事件触发使用 @event="method",而通过 provide/inject 机制使用 provide() 和 inject()。

如何在 Vue 中调用组件方法

直接调用

要直接调用一个组件方法,请使用 $refs 对象:

// 父组件<template><childcomponent ref="child"></childcomponent></template><script>  export default {    methods: {      callChildMethod() {        this.$refs.child.childMethod(); // 直接调用子组件中的 childMethod 方法      }    }  }</script>

通过事件触发

另一种调用组件方法的方法是通过事件触发:

// 父组件<template><childcomponent></childcomponent></template><script>  export default {    methods: {      callChildMethod(payload) {        // 接收 childMethod 方法传递的 payload      }    }  }</script>
// 子组件<template><button>触发方法</button></template><script>  export default {    methods: {      childMethod() {        this.$emit('trigger-method', { payload: '数据' }); // 发送事件触发父组件中的方法      }    }  }</script>

通过 provide/inject

对于需要跨多个组件层级调用的方法,可以使用 provide/inject 机制:

// 父组件<template><childcomponent></childcomponent></template><script>  export default {    provide() {      return {        callChildMethod: this.callChildMethod      }    },    methods: {      callChildMethod() {        // ...      }    }  }</script>
// 子组件<template><grandchildcomponent></grandchildcomponent></template><script>  export default {    inject: ['callChildMethod'],    methods: {      callParentMethod() {        this.callChildMethod(); // 通过 provide 注入的方法调用父组件中的方法      }    }  }</script>