父组件修改子组件数据的几种方式!
条件: vue setup
方法一:父组件通过子组件的暴露的接口修改数据
组件test.vue代码:
<template>
<view>姓名:{{student.name}}</view>
<view>年龄:{{student.age}}</view>
<view>手机:{{student.contact.phone}}</view>
<view>企鹅:{{student.contact.qq}}</view>
<view>邮箱:{{student.contact.email}}</view>
<view>学生数量:{{studentNumber}}</view>
</template>
<script setup>
import {
ref,
reactive,
toRefs
} from 'vue'
var student = reactive({
name: '张三',
age: 15,
contact: {
phone: '18714896998',
qq: '103422412',
email: 'wm218@qq.com'
}
})
var studentNumber = ref(20)
defineExpose({
// ...student, 如果采用这种方式展开,暴露出的数据将不会同步
...toRefs(student), // 必需要通过toRefs数据才能同步
studentNumber // 这里的数据可以同步
})
</script>
父组件修改数据,子组件同步响应示例:
<template>
<test ref="student"></test>
</template>
<script setup>
import {
ref,
toRef,
toRefs,
reactive,
onMounted
} from 'vue'
// 获取组件实例,必需在setup内才能获取
let student = ref(null);
var info
// 获取组件值,必需要挂载完成之后才能获取
onMounted(() => {
// 延迟5秒查看变化
setTimeout(() => {
// 这里有二个细节:
// 1. 获取组件对外暴露接口,采用 student._value 方式
// 2. 必需定义成动态响应式的(toRefs或toRef转换),否则暴露的数据为只读
// info = reactive({...student._value}) 这种方式也不行
info = {
...toRefs(student._value) //将组件值扩展开,并是响应式的
}
info.studentNumber.value = 50 // 修改此处,将会同步更新到组件
info.name.value = '李四' // 修改此处,将会同步更新到组件
}, 5000)
});
</script>
方法二:子组件通过自定义事件对父组件暴露内部数据接口
子组件test.vue
<template>
<view>{{student.name}}</view>
<button @click="sendInfo">点击传递学生信息到父组件</button>
</template>
<script setup>
import {
reactive,
getCurrentInstance
} from 'vue'
// 要暴露的数据
var student = reactive({
name: '张三',
age: 15,
contact: {
phone: '18714896998',
qq: '103422412',
email: 'wm218@qq.com'
}
})
// 定义:自定义事件
defineEmits(['getInfo'])
// 获取当前实例(必需放在setup内)
var instance = getCurrentInstance()
function sendInfo() {
instance.emit('getInfo', student) //执行自定义事件
}
</script>
父组件:
<template>
<test ref="student" @getInfo="printStudent"></test>
</template>
<script setup>
function printStudent(data) {
data.name = '王五'
}
</script>

浙公网安备 33010602011771号