Vue3.0的父子传值

本文介绍了Vue3.0中父子组件之间的通信方式。对于父组件向子组件传值,需将数据转化为响应式然后绑定。子组件向父组件传值则通过自定义事件实现。
摘要由CSDN通过智能技术生成

Vue3.0的父子传值

1.父组件向子组件传值

父组件:

<template>
<div>
    <h1>父组件<h1>
    <hr>
    <son :money="money">
</div>
</template>
<script>
import {ref} from 'vue'
import son from './son.vue'
export default {
  name:'App',
  components:{
    Son
}
//父组件的数据传递给子组件
setup(){
  const money = ref(100);
  return {money}
}
}
</script>

注:Vue3.0中父组件向子组件中传值和Vue2.0中传值一样只不过要按照Vue自己的方式将自己的数据变成响应式的数据进行绑定。

子组件:

<template>
<div>
    <h1>子组件</h1>
    <hr>
    <div>{
  {money}}</div>
</div>
</template>
<script>
    import {onMounted} from 'vue'
    export default{
        name:'App',
         props:{
                money:{
                    type:Number
在Vue 3.0中,父子组件之间的传值可以使用props和emit实现。props是父组件向子组件传递数据的一种方式,子组件通过声明props来接收父组件传递的值。父组件可以将数据通过属性的形式绑定到子组件上,子组件可以在props属性中声明接收该属性的类型和默认值。例如: 父组件代码: <template> <div> <child-component :message="parentMessage"></child-component> </div> </template> <script> import ChildComponent from "./ChildComponent.vue"; export default { components: { ChildComponent, }, data() { return { parentMessage: "Hello from parent", }; }, }; </script> 子组件代码: <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { props: { message: { type: String, default: "", }, }, }; </script> 在这个例子中,父组件传递了一个名为parentMessage的数据到子组件中,子组件使用props接收到父组件传递的message,并在模板中显示出来。 除了props,Vue 3.0还引入了新的API emit,它可以用于在子组件中向父组件发送消息。子组件可以通过$emit方法发送一个自定义事件,并可以传递需要发送的数据。父组件可以通过在子组件上监听该事件,并在回调中接收子组件发送的数据。例如: 子组件代码: <template> <div> <button @click="sendMessage">Send Message</button> </div> </template> <script> export default { methods: { sendMessage() { this.$emit("messageSent", "Hello from child"); }, }, }; </script> 父组件代码: <template> <div> <child-component @messageSent="handleMessage"></child-component> </div> </template> <script> import ChildComponent from "./ChildComponent.vue"; export default { components: { ChildComponent, }, methods: { handleMessage(message) { console.log(message); }, }, }; </script> 在这个例子中,子组件中的按钮点击事件调用sendMessage方法,该方法使用$emit发送一个名为messageSent的自定义事件,并将"Hello from child"作为参数传递。父组件在模板中使用@messageSent监听该事件,并通过handleMessage方法处理接收到的消息。在handleMessage方法中,我们打印出了从子组件发送的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值