vue2 父子组件通讯

父传子

父组件:app.vue

<template>
  <div>
    app 父组件
    <!-- 2.动态绑定定义的数据 -->
    <LiCount :title="mytitle"></LiCount>
  </div>
</template>

<script>
import LiCount from "./components/LiCount.vue";
export default {
  components: {
    LiCount,
  },
  // 1.在父组件中,定义一个data变量
  data() {
    return {
      mytitle: "父传子传递的数据",
    };
  },
};
</script>

<style scoped></style>

子组件:LiCount.vue

<template>
  <div class="cssaa">
    子组件:
    <!-- 4.显示到页面上 -->
    {{title}}
  </div>
</template>

<script>
export default {
  // 3.通过props接收父组件传递过来的数据
  props:['title']
}
</script>

<style scoped>
.cssaa{
  border: 1px solid rgb(12, 12, 12);
  /* 圆角边框 */
  border-radius: 10px;
}
</style>

子传父

子组件:LiCount.vue

<template>
  <div class="cssaa">
    子组件
    <!-- 1.点击事件 -->
    <button @click="changeFn">修改</button>
  </div>
</template>

<script>
export default {
  methods: {
    changeFn() {
      // 2.通过$emit,向父组件传递数据,并传递一个参数
      this.$emit("changeTitle", "子组件传递给父组件的数据");
    },
  },
};
</script>

<style scoped>
.cssaa {
  border: 1px solid rgb(12, 12, 12);
  border-radius: 10px;
}
</style>

父组件:app.vue

<template>
  <div>
    <!-- 6.在页面中显示 -->
    父组件接收的数据:{{ newTitle }}
    <!-- 3.父组件对消息进行监听 -->
    <LiCount @changeTitle="changeCount"></LiCount>
  </div>
</template>

<script>
import LiCount from "./components/LiCount.vue";
export default {
  components: {
    LiCount,
  },
  data() {
    return {
      // 5.定义数据
      newTitle: "",
    }
  },
  methods: {
    // 4. 提供处理函数
    changeCount(newTitle) {
      this.newTitle = newTitle;
    },
  },
};
</script>

<style scoped></style>

流程图

父传子

 子传父

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值