Vue3 ts $refs 父组件修改子组件数据
一、父组件
1、声明子组件ref
<Child1 ref="c1"></Child1> <Child2 ref="c2"></Child2>
2、点击事件传递$refs参数
<button @click="changeData($refs)">修改所有子组件数据</button>
3、通过$refs获取子组件的数据,通过方法进行操作数据
二、子组件
对外暴露数据
defineExpose({game, xx})
三、案例
父组件
<template> <Child1 ref="c1"></Child1> <Child2 ref="c2"></Child2> <button @click="changeData($refs)">修改所有子组件数据</button> </template> <script setup lang="ts" name="App"> import Child1 from './components/Child1.vue'; import Child2 from './components/Child2.vue'; function changeData(refs:any){ refs.c1.computer = "戴尔" refs.c2.game = "原神" } </script>
子组件一
<template> <div>子组件1</div> <div>电脑:{{ computer }}</div> </template> <script setup lang="ts" name="Child1"> import { ref } from 'vue'; let computer = ref("联想") defineExpose({computer}) </script>
子组件二
<template> <div>子组件2</div> <div>游戏:{{ game }}</div> </template> <script setup lang="ts" name="Child2"> import { ref } from 'vue'; let game = ref("王者荣耀") // 对外暴露 defineExpose({game}) </script>