欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue3学习笔记-setup

程序员文章站 2022-05-17 20:38:31
...

是什么

组合(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

    father

     <child >
          <template v-slot:slot1>
            <h1>使用slot1</h1>
          </template>
    
          <template v-slot:slot2>
            <p>使用slot2</p>
          </template>
      </child>
    

    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

    child

    <template>
      <div>
        <button @click="show">子组件</button>
      </div>
    </template>
    
    <script>
    export default {
      setup(props, context) {
        function show(){
            context.emit('childShow','来自子组件')
        }
        return {show}
      },
    };
    </script>
    

    father

    <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])
  }
}
相关标签: vue vue.js