父子组件传值
1.父组件向子组件传递
父组件
传递非字符串类型需要使用v-bind
<template>
<div class="layout">
<Menu v-bind:data="data" title="我是标题"></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'
import { reactive } from 'vue';
const data = reactive<number[]>([1, 2, 3])
</script>
子组件
通过defineProps 来接受
defineProps是无须引入的直接使用即可
<template>
<div class="menu">
菜单区域 {{ title }}
<div>{{ data }}</div>
</div>
</template>
// ts版本
<script setup lang="ts">
defineProps<{
title:string,
data:number[]
}>()
</script>
// js版本
<script setup>
defineProps({
title:{
default:"",
type:string
},
data:Array
})
</script>
2.子组件向父组件传参
子组件通过defineEmits派发一个事件
<template>
<div class="menu">
<button @click="clickTap">向父组件传参</button>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
const list = reactive<number[]>([1, 2, 3])
const emit = defineEmits(['on-click'])
const clickTap = () => {
emit('on-click', list)
}
</script>
父组件接受子组件的事件
<template>
<div class="layout">
<Menu @on-click="getList"></Menu>
<div class="layout-right">
<Header></Header>
<Content></Content>
</div>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import Menu from './Menu/index.vue'
import Header from './Header/index.vue'
import Content from './Content/index.vue'
const data = reactive<number[]>([4, 5, 6])
const getList = (list: number[]) => {
console.log(list,'父组件接受到了子组件');
}
</script>
|