父组件向后代组件传递响应式数据以及在子组件中更改数据内容
方法:
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>
点击查看代码
<script setup>
import fromMyComponent from "./fromMyComponent.vue";
components: { fromMyComponent }
</script>
<template>
<div>
<h1>我是myComponent</h1>
myComponent的子组件:<from-my-component/>
</div>
</template>
<style scoped>
</style>
点击查看代码
<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>

浙公网安备 33010602011771号