vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3父子组件通信方式

Vue3中父子组件之间相互通信的方式详解

作者:Danta

本文主要探讨了 Vue 3 中父子组件之间的通信方式,包括父传子,通过props传递数据和方法;子传父,用emit触发自定义事件并传递数据;还介绍了使用ref直接操作子组件实例,借助defineExpose暴露子组件的属性和方法给父组件,需要的朋友可以参考下

前言

父子组件通信,作为Vue应用开发中不可或缺的一部分,是实现数据流动、事件触发以及组件间互动的关键机制。无论是简单的属性传递,还是复杂的交互逻辑,掌握这一技能对于构建富有层次感和互动性的用户界面至关重要。通过学习如何有效地利用props进行数据下行传递,使用emit触发自定义事件,以及借助ref直接操作子组件。本文将详细探讨Vue 3中的父子组件通信,帮助你深入了解并掌握这些核心概念。

父传子

使用Props传递数据和方法

在Vue中,父组件向子组件传递数据最常用的方法是通过propsprops允许父组件以一种声明式的方式向下传递数据到子组件。这种方式不仅简化了数据流的管理,还确保了组件之间的单向数据绑定,使得状态更易于追踪和调试。

代码模块

App.vue

<script setup>
import ChildComponent from './components/ChildComponent.vue'
import { ref } from 'vue'
const title=ref("来自父组件的消息")
const method =()=>{
    console.log("来自父组件的方法")
}
</script>

<template>
   <div>
   
      <h2>父组件</h2>
       <ChildComponent :title="title" :parentmethod="method" />
   </div>
</template>

<style scoped>

</style>

解析:

ChildComponent.vue

<template>
    <div>
      在子组件中: {{props.title}}
      <button @click="props.parentmethod">子组件调用父组件的方法</button>
    </div>
</template>

<script setup>
import {
    defineProps,
    ref
} from 'vue'
const props=defineProps({
    title:{
        type:String,
        required:true
    },
    parentmethod:{
        type:Function,
        required:true
    }

})
</script>

<style  scoped>

</style>

效果:

子传父

使用Emit触发自定义事件

子组件与父组件通信的主要方式之一是通过emit触发自定义事件。当子组件想要通知父组件某个特定事件发生时,它可以调用emit来触发一个命名事件,并可以选择性地传递额外的数据。 App.vue

<script setup>
import ChildComponent from './components/ChildComponent.vue'
import { ref } from 'vue'
const title=ref("来自父组件的消息")
const method =()=>{
    console.log("来自父组件的方法")
}
const messageFromChild=ref("")
const handleChildMessage = (message) => {
    console.log('来自子组件的消息:', message);
    messageFromChild.value=message
    // 在这里可以处理子组件发送的消息
};
</script>

<template>
   <div>
       
      <h2>父组件</h2>
       <ChildComponent :title="title" :parentmethod="method"  @child-message="handleChildMessage"/>
       <p>来自子组件的消息:{{messageFromChild}}</p>
   </div>
</template>

<style scoped>

</style>

ChildComponent.vue

<template>
    <div>
      在子组件中: {{props.title}}
      <hr>
      <button @click="props.parentmethod">子组件调用父组件的方法</button>
      <hr>
      <button @click="childMessage">子组件给父组件发送数据</button>
    </div>
</template>

<script setup>
import {
    defineProps,
    ref,
    defineEmits,

} from 'vue'
const props=defineProps({
    title:{
        type:String,
        required:true
    },
    parentmethod:{
        type:Function,
        required:true
    }

})
const emit = defineEmits(['child-message'])
const childMessage = () => {
    emit('child-message', '我是子组件');
  };
</script>

<style  scoped>

</style>

解析:

效果:

图解:

当我们实现完子组件向父组件,传递信息后,那么长的帅的读者就要问了?怎么向父组件传递方法呢?

使用ref实现子组件对父组件的传递

创建响应式引用:

大家都知道ref 可以用来创建一个响应式的变量,该变量可以被绑定到模板中的元素或组件上。当这个变量的值发生变化时,视图会自动更新。

  import { ref } from 'vue'
    const count = ref(0)

访问子组件实例:

当你需要直接与子组件进行交互时(比如调用子组件的方法或访问它的属性),可以通过给子组件添加 ref 属性来获取子组件的实例。

代码:

我们可以先看子组件向父组件输出了什么? parent组件:

<template>
    <div>
      <Child ref="comp" />
      <button @click="handlerClick">按钮</button>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const comp = ref(null) // 标记DOM 元素  null 组件没用挂载,DOM 也不在 
const title = ref('hello') // 标记数据
const handlerClick = ()=>{
    console.log(comp,comp.value)
   console.log( comp.value.childName)
   comp.value.someMethod()
}

</script>
<style  scoped>
</style>

child组件:

<template>
    <div>
       Child
    </div>
</template>

<script setup>
import {
    defineProps,
    defineEmits,
    defineExpose,
    ref
} from 'vue'
defineExpose({
    childName:"这是子组件的属性",
    someMethod:()=>{
        console.log('这是子组件的方法')
    }
})
</script>
<style  scoped>

</style>

解析:

运行机制

效果:

总结:

以上就是Vue3中父子组件之间相互通信的方式详解的详细内容,更多关于Vue3父子组件通信方式的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文