vue3父子组件传参props

.初始化

  子组件数据:

<template>
  <div>
    我是子组件:{{ sumZ }}
    <button @click="addZ">子组件加加</button>
  </div>
</template>
<script setup>
import {ref} from "vue";
const sumZ = ref(0)// 子组件数据
function addZ() {// 子组件加加
  sumZ.value++
}
</script>

父组件数据:

<template>
  <div>我是父组件:{{ sumF }}
    <button @click="addF">父组件加加</button>
  </div>
  <child></child>
</template>
<script setup>
import {ref} from "vue";
import Child from "./child.vue";
const sumF = ref(200)// 父组件数据
function addF() {// 父组件加加
  sumF.value++
}
</script>

页面效果:

1.子组件获取父组件的值:

父组件添加:name = '' sumF''       (name不重要,但要和子组件的defineProps值对应)

子组件:

子组件通过defineProps获得父组件的值

效果:

2.父传子(父调用子方法):

是通过调用子组件的方法获得的数据

子组件:

父组件:

效果:

3.子调父方法:

父组件有一个弹窗方法

子组件

效果:

4.原代码:

子组件

<template>
  <div>
    我是子组件:{{ sumZ }},  父组件数据:{{ props.name }}
    <button @click="addZ">子组件加加</button>
    <el-button @click="getParentMethod">子组件调用父组件方法</el-button>

  </div>
</template>
<script setup>
import {ref} from "vue";
const sumZ = ref(0)// 子组件数据
function addZ() {// 子组件加加
  sumZ.value++
}

const props = defineProps({
  name: {
    type: Object,
  }
})

// 子传父:子组件需要暴露方法给父组件调用
const getChildNum = () => {
  return sumZ.value
}
defineExpose({
  getChildNum // 暴露方法
})

//3.子组件调用父组件方法
const emits = defineEmits([])
const getParentMethod = () => {
  emits('alert', '你好')
}
</script>

父组件:

<template>
  <div>我是父组件:{{ sumF }},子组件:{{msg}}
    <button @click="addF">父组件加加</button>
    <el-button @click="getChildNum">获取子组件数据</el-button>
  </div>
  <child :name="sumF" ref="childRef" @alert="checkAdd"></child>
</template>
<script setup>
import {ref} from "vue";
import Child from "./child.vue";
const sumF = ref(200)// 父组件数据
function addF() {// 父组件加加
  sumF.value++
}


const childRef = ref();
const msg = ref(0)

// 父组件获取子组件数据
const getChildNum = () => {
  msg.value = childRef.value.getChildNum()
}

// 父组件调用子组件方法
// 接受参数,打印参数
const checkAdd = (value) =>{
  alert(value)

}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值