.初始化
子组件数据:
<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>