组件通信-props
props 是使用频率最高的一种通信方式,父>子 子>父
- 父传子:属性值 是非函数
- 子传父:属性值 是函数
父组件
<script setup lang="ts">
import { ref } from 'vue'
import Child from './Child.vue'
const car = ref('奥迪')
const toy = ref('')
const getToy = (value: string) => {console.log('接收到子组件传递过来的玩具', value);toy.value = value
}
</script><template><div class="father"><h1>父组件</h1><h4>父的车:{{ car }}</h4><h4 v-if="toy">子给的玩具:{{ toy }}</h4><Child :car="car" :sendToy="getToy" /></div></template>
子组件
<script setup lang="ts">
import { ref } from 'vue'
defineProps(['car', 'sendToy'])
const toy = ref('奥特曼')
</script><template><div class="child"><h1>子组件</h1><h4>子的玩具:{{ toy }}</h4><div>父给的车:{{ car }}</div><button @click="sendToy(toy)">把玩具传递给父亲</button></div></template>