Vue中的父子组件通信

文章详细阐述了Vue中如何通过Prop实现父组件向子组件单向传递数据,以及子组件如何通过$emit触发事件来向父组件传递信息。文中以BlogTitle和ButtonCom子组件为例,展示了props的声明、默认值和类型检查,以及setup函数在Vue3中的作用。同时,还解释了Vue的响应式原理在ref和reactive中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue中的Prop属性 - 父传子

Prop的作用为父组件向子组件单向传递数据,这是一个单向数据流。父级prop的数据更新会向下流动到子组件中。

  1. 子组件 BlogTitle.vue

    在子组件中声明props属性,用来接收父组件传递的数据。

    <template>
      <div class="son">
        <h1>这是子组件</h1>
        <h3>{{ title }}</h3>
        <h3>{{ age }}</h3>
        <h3>{{ sex }}</h3>
      </div>
    </template>
    
    <script>
    export default {
      name: "BlogTitle",
      //接受并对数据进行检测
      props:{
        title: String,
        age: {
          type: Number,
          default: 99 //默认值
        },
        sex: {
          type: String,
          required: true
        }
      },
      setup(props){
        console.log(props.title);
      }
    }
    </script>
    
  2. 父组件 BlogView.vue

    先在script中引用BlogTitle.vue,然后在components属性加入子组件名称。

    最后,可在setup中定义需要传输的数据。

    <template>
      <div class="father">
        <h1>这是父组件</h1>
        <BlogTitle :title="msg" sex="男" />
        <h1>--------------</h1>
        <BlogTitle v-for="post in this.posts"
              :key="post.id"
              :title="post.title"
        />
      </div>
    </template>
    
    <script>
    // 1. 引用BlogTitle.vue
    import BlogTitle from "@/components/BlogTitle";
    import {reactive, ref} from 'vue'
    
    export default {
      name: "BlogView",
      //2. 加入BlogTitle
      components: {
        BlogTitle
      },
      //
      setup() {
        const msg = ref("这是标题");
        /**
         * 1. ref()和reactive()一样,都是实现响应式数据的方法。
         * 2. reactice()必须传递一个对象,而ref可以实现简单值的监听。
         * 3. ref本质为reactice, ref(xxx) -> reactice({value:xx})
         * 
         */
        //3. 定义传输的数据
        const posts = reactive([
          {id: 1, title: 'My journey with Vue'},
          {id: 2, title: 'Blogging with Vue'},
          {id: 3, title: 'Why Vue is cool'}
        ]);
        
        return {posts, msg};
      }
    }
    </script>
    

Vue3的特性函数 - setup

  1. setup函数处于beforeCreate和Created两个钩子函数之间的函数。setup无法使用data和methods中的数据和方法。
  2. 在setup函数中定义的变量和方法最后都是需要return出去的,不然无法在模板中使用

vue组件通信 - 子传父

子传父

  1. 需要触发一个事件,在这个事件中使用this.$emit(“父组件使用的事件名”,“子组件的数据”),
  2. 通过$emit事件名抛出,父组件调用抛出的事件名,并获取到子组件的传输来的数据。

子组件 ButtonCom.vue

<template>
  <h3>{{ title }}</h3>
   <button @click="onCount">{{ this.count }}</button>
  <!-- 1. 组件事件 : 通过内置方法$emit()方法,将事件名称抛出一个事件-->
  <!-- this.$emit("父组件使用的事件名","子组件的数据"),-->
  <button @click="$emit('enlarge-text',this.postFontSize)">Enlarge Text</button>
</template>
<script>
export default {
  //通过props, 父组件中定义的数据就可以传递到组件实例上。
  //字符串组声明props
  props: ['title'],
  //对象的形式声明props

  //2. 声明需要抛出
  emits: ['enlarge-text'],
  data() {
    return {
      count: 0,
      //子组件需要传递的数据
      postFontSize: 1
    }
  },
  methods: {
    onCount() {
      this.count++;
    }
  },
  name: "ButtonCom"
}
</script>

父组件HomeView.vue

<template>
  <div>
      <div :style="{fontSize: postFontSize + 'em'}">
        <!-- 1. @后为子组件中的$emit('enlarge-text',1)定义的事件名 -->
        <ButtonCom
            v-for="post in this.posts"
            :key="post.id"
            :title="post.title"
            @enlarge-text="AddFontSize"
        >
        </ButtonCom>
      </div>
  </div>
</template>


<script>
// 引用并使用组件
import ButtonCom from '@/components/ButtonCom.vue'
export default {
  name: 'HomeView',
  data() {
    return {
      posts: [
        {id: 1, title: 'My journey with Vue'},
        {id: 2, title: 'Blogging with Vue'},
        {id: 3, title: 'Why Vue is so fun'}
      ],
      postFontSize:1
    }
  },
  //组件都被挂载后执行。通常模板渲染成html后调用,在对html的dom节点进行一些操作。
  //确保渲染页面中 DOM的相关操作被客户端执行
  mounted() {
  },
  methods: {
    //2. 这里接受的n为 $emit('enlarge-text',4) 的4。
    AddFontSize(n){
      this.postFontSize += n;
    }
  },
  components: {
    ButtonCom
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值