父子组件传参 父组件给子组件传参 父组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <template> <div class="layout"> <Menu title="ler-jiu" :data="data"></Menu> <div class="layout-right"> <Header></Header> <Content></Content> </div> </div> </template> <script setup lang="ts"> import Menu from './Menu/index.vue' import Header from './Header/index.vue' import Content from './Content/index.vue' let data = { name:'ler-jiu', age:18 } </script>
子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <template> <div class="menu"> Menu <div> {{title}} </div> <div> {{data}} </div> </div> </template> <script setup lang="ts"> type Props = { title:string, data:{ name:string, age:number } } defineProps<Props>() </script>
父组件传参时,string类型可不用v-bind绑定,其他类型需要v-bind绑定(可以简写为:)。
子组件通过defineProps来定义接受的参数。
withDefaults设置默认值
对于数组、对象等引用类型属性,为了避免赋值为引用,规定必须包装成一个函数return默认值。
1 2 3 4 5 6 7 8 9 withDefaults (defineProps<Props >(), { title :'menu' , data : () => { return { name :'user' , age :0 } } })
子组件给父组件传参 为子组件注册事件,父组件为事件绑定函数,即可获得子组件调起绑定函数时所传递的参数。
子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <template> <div class="menu"> Menu <div> <button @click="click">触发event</button> </div> <div> <button @click="click2">触发event2</button> </div> </div> </template> <script setup lang="ts"> const emit = defineEmits(['event', 'event2']) const click = () => { emit('event', false, 10086) } const click2 = () => { emit('event2', true, 10010) } </script>
父组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <template> <div class="layout"> <Menu @event="menuClick" @event2="menuClick2"></Menu> <div class="layout-right"> <Header></Header> <Content></Content> </div> </div> </template> <script setup lang="ts"> import Menu from './Menu/index.vue' import Header from './Header/index.vue' import Content from './Content/index.vue' const menuClick = (flag:boolean, phone:number) => { console.log(flag, phone) } const menuClick2 = (flag:boolean, phone:number) => { console.log(flag, phone) } </script>
子组件向外暴露属性 子组件
1 2 3 4 5 let dataList = ref ([1 ,2 ,5 ,9 ])defineExpose ({ dataList })
父组件
通过ref获取子组件实例,在defineExpose中暴露的属性可以直接进行访问与修改。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <template> <div class="layout"> <Menu ref="menus"></Menu> <div class="layout-right"> <button @click="getMenuData"></button> <Header></Header> <Content></Content> </div> </div> </template> <script setup lang="ts"> import Menu from './Menu/index.vue' import Header from './Header/index.vue' import Content from './Content/index.vue' import {ref} from "vue"; let menus = ref(null) const getMenuData = () => { console.log(menus.value.dataList) } </script>