父组件向后代组件传递响应式数据以及在子组件中更改数据内容

方法:
1、父组件使用provide提供数据和修改数据的函数
2、后代组件使用inject接收数据并触发函数
完整代码:
1、App.vue

点击查看代码
<script setup>
import{provide,ref}from 'vue'
import myComponent from "./components/myComponent.vue"
const count=ref(0)
provide('codekey',count)
const dianji=()=>{
  count.value++
}
provide('setcountkey',dianji)
</script>

<template>
  <div>
    <h1>我是App组件</h1>
   App的子组件:<myComponent/>
  </div>
</template>

<style scoped>
</style>

2.myComponent.vue
点击查看代码
<script setup>
import fromMyComponent from "./fromMyComponent.vue";
  components: { fromMyComponent }
</script>
<template>
  <div>
    <h1>我是myComponent</h1>
    myComponent的子组件:<from-my-component/>
  </div>
</template>
<style scoped>

</style>
3.fromMyComponent.vue(app的后代组件,myComponent的子组件)
点击查看代码
<script setup>
import{inject}from 'vue'
const msg=inject('codekey')
const dianji=inject('setcountkey')
</script>
<template>
  <div>
   <h2>我是fromMyComponent,我接收到的数据是:</h2>
   <button @click="dianji">{{ msg }}</button>
  </div>
</template>
<style>
button{
  height: 30px;
  width: 30px;
}
</style>

posted @ 2024-07-24 10:59  xjZhang  阅读(131)  评论(0)    收藏  举报