vue3父子组件传值 父组件传值给子组件嵌套子组件

用一个tabs组件举例

父组件:

<Mytabs2 @handleTabsChange="handleTabsChange" :tabsList="tabsList_data">
    <template #tab1>
    </template>
    <template #tab2>
    </template>
</Mytabs2>
<script setup>
  
const tabsList_data = reactive(

    [
        {
            id: 0,
            value: '数据图表',
            isActive: false
        }, {
            id: 1,
            value: '访问记录',
            isActive: true
        }]
)
//父组件接收值 在子组件上加 @handleTabsChange="handleTabsChange"
const handleTabsChange = (e) => {
    const index = e[0]
    const item = e[1]
    console.log(index, item);
    // 将isActive值全部设置为false
    tabsList_data.forEach((item, i) => {
        item.isActive = false
    })
    // 点击的tabisActive设置为true
    tabsList_data[index].isActive = true
}
</script >

子组件:

<template>
    <div>
        <div class="tabs">
            <div class="left">
                <div 
                    v-for="(item,index) in tabsList" :key="item.id" :class="[item.isActive ? 'active' : '', 'tab_item']"
                    @click="handleTabsChange_c(index,item.value)">
                    {{ item.value }}
                </div> 
            </div>
            <div class="right">
                <slot name="tab_right"></slot>
            </div>
    </div>
    <div class="tabs_content">
            <div v-if="tabsList[0].isActive">
                <slot name="tab1"></slot>
            </div>
            <div v-else-if="tabsList[1].isActive">
                <slot name="tab2"></slot>
            </div>
            <div v-else-if="tabsList[2].isActive">
                <slot name="tab3"></slot>
            </div>
            
        </div>
    </div>
</template>
<script setup>
  //接收父组件传过来的值 let props=defineProps({ tabsList: { type: Array }, }); console.log(props.tabsList);
  //子组件向父组件传值 const emit
= defineEmits(['handleTabsChange']) const handleTabsChange_c = (index,item)=>{ emit('handleTabsChange',[index,item]); } </script> <style lang="scss" scoped> .tabs { display: flex; justify-content: space-between; align-items: center; padding-bottom: 16px; .left{ display: flex; } .tab_item { cursor: pointer; margin-right: 24px; } .tab_item.active { color: #165DFF; border-bottom: 2px solid #165DFF; padding-bottom: 8px; } } </style>

子组件嵌套传值给父组件:

UoDrawer组件嵌套使用MyTabs2组件

 

 

 

 

 

 父组件:

 

 

 script方法

const handleTabsChange_other = (e) => {
    const index = e[0]
    const item = e[1]
    if (item == '高级配置') {
        UoDrawer_width.value = '940'
    }
    else {
        UoDrawer_width.value = '720'
    }
    // 将isActive值全部设置为false
    tabsList_other.forEach((item, i) => {
        item.isActive = false
    })
    // 点击的tabisActive设置为true
    tabsList_other[index].isActive = true
}

 

子组件向父组件多传了一次而已。

posted @ 2023-03-16 16:10  seven&night  阅读(747)  评论(0编辑  收藏  举报