目录
一、父传子
父组件
<template> <div class="fa"> <h2>父组件</h2> <p>a={ { a }}</p> <!-- @change用来接收子传父,然后通过事件 --> <Son :a="a"></Son> <button @click="add">+</button> </div> </template> <script setup> import Son from './Son.vue'; import { ref } from 'vue'; const a=ref(100) const add=()=>{ a.value++ } </script> <style> .fa{ border:1px solid black; height: 300px; width: 300px; } </style>
子组件:
<template> <div class="son"> <h3>子组件</h3> <p>a={ { a }}</p> </div> </template> <script setup> const props=defineProps({ a:Number }) </script> <style> .son{ border: 1px solid red; width: 200px; height: 200px; } </style>
二、子传父
父组件:
<template> <div class="fa"> <h2>父组件</h2> <p>a={ { a }}</p> <!-- @change用来接收子传父,然后通过事件 --> <Son :a="a" @changea="changeFn"></Son> </div> </template> <script setup> import Son from './Son.vue'; import { ref } from 'vue'; const a=ref(100) const changeFn=(newvalue)=>{ a.value-=newvalue } </script> <style> .fa{ border:1px solid black; height: 300px; width: 300px; } </style>
子组件:
<template> <div class="son"> <h3>子组件</h3> <p>a={ { a }}</p> <button @click="change">修改a的值</button> </div> </template> <script setup> const props=defineProps({ a:Number }) const emit=defineEmits(['changea']) const change=()=>{ // 第一个参数与上面宏定义的名字一致,第二个就是传递的参数 emit('changea',10) } </script> <style> .son{ border: 1px solid red; width: 200px; height: 200px; } </style>