vue3的新寫法和特性整理——六、插槽的使用


1、子組件暴露插槽的寫法

<template>
  <div class="hello">
    <h1>子組件</h1>
    <h1>↓↓↓以下是默認插槽內容↓↓↓</h1>
    <slot :scope="sexEn1"></slot>
    <h1>↑↑↑以上是插槽內容↑↑↑</h1>
    <br />

    <div>{{sexEn}}</div>
    <h1>↓↓↓以下是具名插槽 sex的內容↓↓↓</h1>
    <slot name="sex" :scope="sexEn2"></slot>
    <h1>↑↑↑以上是具名插槽 sex的內容↑↑↑</h1>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue';
export default {
  setup(a,b) {
    console.log(b);
    const state = reactive({
      sexEn1: 'femeal',
      sexEn2: 'meal',
      age: 23
    });
    return {
      ...toRefs(state)
    };
  },
  name: 'AgeAndSex'
};
</script>

<style scoped>
.hello {
  margin: 20px;
  color: green;
  border: 1px solid green;
}
.pointer {
  cursor: pointer;
}
</style>

  
2、父組件使用插槽的寫法

<template>
  <div class="about">
    <AgeAndSex>
      <template v-slot="obj">
        <div class="slot">父組件使用插槽反顯sexEn1:{{obj.scope}}為{{filter(obj.scope)}}</div>
      </template>
      <template v-slot:sex="obj">
        <div class="slot">父組件使用插槽反顯sexEn2:{{obj.scope}}為{{filter(obj.scope)}}</div>
      </template>
    </AgeAndSex>
  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import { reactive, toRefs } from 'vue';
import AgeAndSex from '@/components/AgeAndSex';
export default {
  setup() {
    let filter = e => {
      console.log(e);
      switch (e) {
        case 'meal':
          return '男';
        case 'femeal':
          return '女';
        default:
          return '保密';
      }
    };
    return {
      filter
    };
  },
  filters: {},
  components: { AgeAndSex }
};
</script>
<style scoped>
.slot {
  color: red;
}
</style>

  效果圖

 

 

3、順帶一提:在vue3中,已經廢除了管道符(過濾器)的功能,官方提出使用計算屬性的解決方案。如果復用性不高,也可以在setup中寫方法,或者寫在工具函數里(我個人想法是掛載到window上,然后在setup中的返回值中解構)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM