您的位置:首页 > 新闻 > 热点要闻 > vue中ref与$parent/$children⽗⼦组件通信例子

vue中ref与$parent/$children⽗⼦组件通信例子

2025/6/6 20:48:07 来源:https://blog.csdn.net/codemami/article/details/139569521  浏览:    关键词:vue中ref与$parent/$children⽗⼦组件通信例子

在 Vue.js 中,ref 主要用于在模板中直接访问 DOM 元素或子组件实例,而 $parent 和 $children 主要用于在组件内部访问父组件和子组件实例,但通常不推荐频繁使用 $parent 和 $children 进行组件通信,因为它们会使组件之间的依赖关系变得复杂且难以维护。

不过,为了回答您的问题,我会给出使用这些特性进行通信的例子。

使用 ref

假设我们有一个父组件和一个子组件,并且我们想在父组件中直接访问子组件的某个方法或数据。

子组件 (ChildComponent.vue)

vue

<template>

  <div>

    <button @click="sayHello">Hello from Child</button>

  </div>

</template>

<script>

export default {

  methods: {

    sayHello() {

      console.log('Hello from Child method!');

    }

  }

}

</script>

父组件 (ParentComponent.vue)

vue

<template>

  <div>

    <ChildComponent ref="childRef" />

    <button @click="callChildMethod">Call Child Method</button>

  </div>

</template>

<script>

import ChildComponent from './ChildComponent.vue';

export default {

  components: {

    ChildComponent

  },

  methods: {

    callChildMethod() {

      this.$refs.childRef.sayHello(); // 直接访问子组件的方法

    }

  }

}

</script>

 

使用 $parent 和 $children

虽然不推荐,但这里是一个简单的例子。

子组件 (ChildComponent.vue)

vue

<template>

  <div>

    <p>{{ message }}</p>

  </div>

</template>

<script>

export default {

  data() {

    return {

      message: 'Hello from Child'

    }

  },

  mounted() {

    console.log(this.$parent.parentMessage); // 访问父组件的数据

  }

}

</script>

父组件 (ParentComponent.vue)

vue

<template>

  <div>

    <p>{{ parentMessage }}</p>

    <ChildComponent />

    <button @click="showChildMessages">Show Child Messages</button>

  </div>

</template>

<script>

import ChildComponent from './ChildComponent.vue';

export default {

  components: {

    ChildComponent

  },

  data() {

    return {

      parentMessage: 'Hello from Parent'

    }

  },

  methods: {

    showChildMessages() {

      // 注意:这里我们假设只有一个子组件,如果有多个,需要遍历 this.$children

      console.log(this.$children[0].message); // 访问子组件的数据

    }

  }

}

</script>

注意事项

尽量避免使用 $parent 和 $children,因为它们会使组件之间的依赖关系变得复杂且难以维护。

更好的方式是使用 props 和 events 进行父子组件之间的通信,使用 Vuex 进行跨组件通信,或者使用 provide/inject 进行非父子组件之间的通信。

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com