父组件向子组件传递数据
子组件test1
<template> <h>{{myid}}</h> </template> <script> import {reactive,toRefs} from "vue" export default { name: "Test1", props:["id"], setup(props){ const state=reactive({ myid:props.id }) return { ...toRefs(state) } } } </script>
父组件test2
<template> <test1 v-for="item in posts" :key="item.id" :id="item.id"></test1> </template> <script> import {reactive,toRefs} from "vue" import test1 from "./Test1.vue" export default { name: "Test2", components:{ test1 }, setup(){ const state=reactive({ posts:[ {id:1}, {id:2}, {id:4} ] }) return{ ...toRefs(state) } } } </script>
子组件向父组件传递数据
子组件test1
<template> <button @click="clickbutton">点击按钮</button> </template> <script> import {reactive,toRefs} from "vue" export default { name: "Test1", setup(props,{emit}){ const state=reactive({ }) const clickbutton=()=>{ emit("event","我是子组件传过来的数据") } return { ...toRefs(state), clickbutton } } } </script>
父组件test2
<template> <test1 @event="handclick">点击</test1> {{test}} </template> <script> import {reactive,toRefs} from "vue" import test1 from "./Test1.vue" export default { name: "Test2", components:{ test1 }, setup(){ const state=reactive({ test:"" }) const handclick=(data)=>{ state.test=data } return{ ...toRefs(state), handclick } } } </script>