天天看點

Vue3入門到精通-setup系列文章目錄

系列文章目錄

  1. Vue3入門到精通-setup
  2. Vue3入門到精通–ref以及ref相關函數
  3. Vue3入門到精通–reactive以及reactive相關函數

創作不易 拒絕白嫖 點個贊呗

關注我,帶你走進前端的世界!!!

是什麼

組合(composition)API的入口

setup 所處的生命周期

  • beforeCreate -> use setup()
  • created -> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

參數(props,context)

props

父元件傳遞的props

father
<template>
  <div>
    <child :dataFromFather="name" >
    </child>
  </div>
</template>

<script >
import { ref } from "@vue/runtime-core";
import child from "./child.vue";
export default {
  components: {
    child,
  },
  setup() {
    let name=ref('來自父元件的資料')
    return {name}
  },
};
</script>
>      
child
props:['dataFromFather'],
    setup(props, context) {
        console.log('dataFromFather=',props.dataFromFather)  
       // 輸出的是  '來自父元件的資料'
   }      

context

  • attrs
  • slots
<child >
      <template v-slot:slot1>
        <h1>使用slot1</h1>
      </template>

      <template v-slot:slot2>
        <p>使用slot2</p>
      </template>
  </child>      
// 定義slot1 和 slot2
<template>
  <div>
    <p>slot1</p>
    <slot name="slot1"></slot>
  </div>
  <div>
    <p>slot2</p>
    <slot name="slot2"></slot>
  </div>
</template>

<script>
export default {
  setup(props, context) {
    console.log("1=", context.slots);
    onMounted: {
      console.log("2=", context.slots);
    }
  },
};
// 這裡的列印結果 
1=和2= 是一緻的,列印的都是Proxy:slot1和slot2
!!!
若是father注釋slot2的使用,那麼隻會列印proxy:slot1
</script>      
  • emit
<template>
  <div>
    <button @click="show">子元件</button>
  </div>
</template>

<script>
export default {
  setup(props, context) {
    function show(){
        context.emit('childShow','來自子元件')
    }
    return {show}
  },
};
</script>         
<template>
  <div>
    <child @childShow='fatherShow'>
    </child>
  </div>
</template>

<script lang='ts'>
import { onMounted } from "@vue/runtime-core";
import child from "./child.vue";
export default {
  components: {
    child,
  },
  setup(props, context) {
    function fatherShow(data:any){
      console.log(data)
    // 這裡輸出的是 ‘來自子元件
    }
    return {fatherShow}
  },
};
</script>
      

使用渲染函數

import { h, ref, reactive } from 'vue'
export default {
  setup() {
    const readersNumber = ref(0)
    const book = reactive({ title: 'Vue 3 Guide' })
    // 請注意,我們需要在這裡顯式地暴露ref值
    return () => h('div', [readersNumber.value, book.title])
  }
}      

繼續閱讀