前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue3中子父组件传值通信的9种方法

vue3中子父组件传值通信的9种方法

作者头像
潜心专研的小张同学
发布2023-08-24 09:33:54
3510
发布2023-08-24 09:33:54
举报
文章被收录于专栏:大前端专属大前端专属

vue3 中子父组件传值通信的 9 种方法#

1 props 传参#

代码语言:javascript
复制
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Child1 from './components/Child1.vue'
import Child2 from './components/Child2.vue'
import Child3 from './components/Child3.vue'
const data = reactive({
  lifebar: 100,
  child1_lifebar: 0
})
const child1ref: {
  value: {
  /**生命值 */
    lifebar: number
  /**加血 */
 addLifebar: () => void
 }
} = ref<T>()
const child2ref = ref()
/**自身加血 */
const addLifebar = () => {
  data.lifebar++
}
/**给队友加血 */
const addTeammateLifebar = () => {
 console.log(child1ref.value)
 console.log(child1ref.value.lifebar)
  child1ref.value?.addLifebar()
}
onMounted(() => {
 console.log('父组件加载完毕')
 console.log(child1ref.value.lifebar)
  data.child1_lifebar = child1ref.value.lifebar
})
</script>
<template>
 <div class="main">
 <div style="height: 60px; display: flex; align-items: center; justify-content: center">
      我是父组件蔡文姬
 <el-space style="margin-left: 5px">
 <el-button @click="addLifebar">给自身增加1点血量</el-button>
 <el-button @click="addTeammateLifebar">1-给子组件1马可波罗加1点血(父组件调用子组件函数)</el-button>
 </el-space>
 </div>
 <div style="height: 100px; display: flex; flex-direction: column; align-items: center; justify-content: start">
 <div><b>父组件蔡文姬信息</b></div>
 <div>
        当前血量:<b>{{ data.lifebar }}</b>
 </div>
 <div>
 <!-- 这里没有自动刷新,暂时没有找到原因 -->
 2-探测到的子组件1马可波罗当前气值(父组件调用子组件参数):<b>{{ data.child1_lifebar }}</b>
 </div>
 </div>
 <div class="box-content">
 <div class="left-box">
 <Child1 ref="child1ref" :lifebar="data.lifebar"></Child1>
 <Child3></Child3>
 </div>
 <div class="right-box"><Child2></Child2></div>
 </div>
 </div>
</template>
<style scoped lang="scss">
.main {
  width: 80%;
  height: 800px;
  margin: auto;
  border: 2px solid yellowgreen;
 .box-content {
    width: 100%;
    height: calc(100% - 200px);
    display: flex;
    justify-content: space-around;
    align-items: center;
 .left-box {
      width: 45%;
      height: 100%;
      border: 2px solid hotpink;
      position: relative;
 }
 .right-box {
      width: 45%;
      height: 100%;
      border: 2px solid hotpink;
 }
 }
}
</style>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-05-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • vue3 中子父组件传值通信的 9 种方法#
  • 1 props 传参#
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档