Vue3 $parent 子组件修改 父组件数据
一、父组件
对外暴露数据
defineExpose({money})
二、子组件
1、通过事件获取父组件对外暴露的数据 $parent
<button @click="changeMoney($parent)">为父赚钱</button>
2、对数据进行操作
function changeMoney(parent:any){ parent.money += 1 }
三、案例
1、父组件
<template> <Child1></Child1> <div>资产:{{ money }}</div> </template> <script setup lang="ts" name="App"> import { ref } from 'vue'; import Child1 from './components/Child1.vue'; let money = ref(-2000) defineExpose({money}) </script> <style scoped> </style>
2、子组件
<template> <div>子组件1</div> <div>电脑:{{ computer }}</div> <button @click="changeMoney($parent)">为父赚钱</button> </template> <script setup lang="ts" name="Child1"> import { ref } from 'vue'; let computer = ref("联想") function changeMoney(parent:any){ parent.money += 1 } </script>