Vue3 父子組件傳值,defineProps,defineEmits,以及父組件調用子組件的方法 defineExpose

前言

父子組件的值傳遞,在vue2中直接使用 props、this.$emit('xxx')即可,在Vue3中有較大的變化,父組件傳遞的值,只有在子組件使用 defineProps、defineEmits接收纔可以使用


 


父子組件值傳遞

需要將父組件的參數使用defineProps,defineEmits承接,如下:

使用案例

// 父組件
<script setup>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  computed,
} from 'vue';
// tabs數據
const tabsData = [
  {
    type: 1,
    text: '111',
  },
  {
    type: 2,
    text: '222',
  },
  {
    type: 3,
    text: '333',
  },
]
const state = reactive({
  // active tab的序號
  activeTabIndex: 2,
});
// 切換tab
const changeTab = (index, tab) => {
  if (state.activeTabIndex === index) {
    return;
  }
  state.activeTabIndex = index;
  ...
};

const { activeTabIndex } = toRefs(state);
</script>

<template>
  ...
  <CustomTabs 
    :activeIndex="activeTabIndex" 
    :tabsData="tabsData"
    @changeTab="changeTab"
  />
  ...
</template>

// 子組件
<script setup>
import useCommonStoreState from '@/hooks/useCommonStoreState';
import { toRefs } from 'vue';

const props = defineProps({
  tabsData: {
    type: Array,
    required: true,
    default: [],
  },
  activeIndex: {
    type: Number,
    default: 0,
    required: true,
  },
});

const emits = defineEmits(['changeTab']);

// 切換tab
const changeTab = (index, tab) => {
  emits('changeTab', index, tab);
};

const { activeIndex, tabsData } = toRefs(props);
</script>
<template>
  <div class="custom-tabs-container" @touchmove.stop>
    <div
      class="tab"
      :class="`${activeIndex === index ? 'active' : ''}`"
      v-for="(tab, index) in tabsData"
      :key="tab.type"
      @click="changeTab(index, tab)"
    >
      <span>{{ tab.text }}</span>
    </div>
  </div>
</template>

 


父組件調用子組件的方法 defineExpose

需要將子組件的方法暴露出來,如下:

使用案例

// 子組件
<script setup>
// 結束loading
const stopLoading = () => {
  // 請求結束關閉loading
  state.listLoading = false;
}

// 開啓error
const startError = () => {
  state.listError = true;
}

defineExpose({
  stopLoading,
  startError
})
</script>
// 父組件
<script setup>
const customListRef= ref(null);

// 獲取大師列表
const queryRichList = async params => {
  try {
   ...
  }catch (error) {
    window.console.log(error);
    state.failed = true;
    // 報錯回調
    vantListRef.value.startError();
  } finally {
    // 請求結束回調,結束loading
    vantListRef.value.stopLoading();
  }
};

<script>
<template>
  <CustomList
    ref="customListRef"
    v-show="list.length"
    :list="list"
    :finished="finished"
    @queryListData="queryRichList(queryParams)"
  >
</template>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章