vue3组件通信
场景一. 父传子
<script setup> import sonCom from "./components/SonCom.vue"; </script> <template> <div class="fatherBody"> <h1>父组件</h1> <sonCom message="父组件传递给子组件的内容" /> </div> </template> <style scoped> .fatherBody { width: 400px; height: 400px; border:1px solid #000; } </style>
子组件用宏函数defineProps接收父组件传递过来的值
<script setup> defineProps({ message: String }) </script> <template> <div class="sonBody"> <h1>子组件</h1> <div>{{ message }}</div> </div> </template> <style scoped> .sonBody { margin: auto; width: 200px; height: 200px; color: #f00; border: 1px solid #f00; } </style>
如果要在js脚本使用父组件传递过来的值, 只需定义一下, 其它不变
<script setup> const props = defineProps({ message: String }) console.log(props.message) </script> <template> <div class="sonBody"> <h1>子组件</h1> <div>{{ message }}</div> </div> </template>
若果父组件需要传递响应式的数据
<script setup> import { ref } from 'vue' import SonCom from "./components/SonCom.vue"; // 传递响应式数据 const count = ref(100) setTimeout(() => { count.value = 300 }, 3000) </script> <template> <div class="fatherBody"> <h1>父组件</h1> <SonCom :count="count" message="父组件传递给子组件的内容" /> </div> </template>
<script setup> const props = defineProps({ message: String, count: Number }) console.log(props.message) </script> <template> <div class="sonBody"> <h1>子组件</h1> <div>{{ message }} <br>父组件传递的响应式数据{{ count }}</div> </div> </template>
场景二. 子传父
<script setup> import { ref } from 'vue' import SonCom from "./components/SonCom.vue"; const sonMsg = ref('') const getMessage = (msg) => { sonMsg.value = msg } </script> <template> <div class="fatherBody"> <h1>父组件</h1> <h2>子组件传递过来的值: {{ sonMsg }}</h2> <SonCom @get-message="getMessage" /> </div> </template> <style scoped> .fatherBody { width: 400px; height: 400px; border:1px solid #000; } </style>
子组件通过编译器宏函数defineEmits传递数据
<script setup> const emit = defineEmits(['get-message']) const sonMsg = () => { emit('get-message', 'this is son message') } </script> <template> <div class="sonBody"> <h1>子组件</h1> <button @click="sonMsg">点击按钮传值给父组件</button> </div> </template> <style scoped> .sonBody { margin: auto; width: 200px; height: 200px; color: #f00; border: 1px solid #f00; } </style>