vue3的setup函数的使用

 

setup的使用:
1.setup 函数时,它将接受两个参数:(props、context(包含attrs、slots、emit))

context包含三个参数,可通过解构方式写
context该上下文对象是非响应式的,可以安全地解构:
 
export default {
  setup(props, { attrs, slots, emit, expose }) {
    // Attribute(非响应式的对象,等价于 $attrs)
    console.log(attrs)
 
    // 插槽(非响应式的对象,等价于 $slots)
    console.log(slots)
 
    // 触发事件(函数,等价于 $emit)
    console.log(emit)
 
    // 暴露公共 property(函数)
    console.log(expose)
  }
}

 

2.setup函数执行时机是在beforeCreated和created两个周期函数之前
3.setup里面没有vue实例,故想通过this访问会是undefined,即第一张图提示文字所述
4.setup函数中所定义的所有变量和方法,谨记要return出去,否则在vue文件(模板)中无法使用
5.在渲染函数中可以直接使用在同一作用域下声明的响应式状态:

import { h, ref } from 'vue'
 
export default {
  setup() {
    const count = ref(0)
    return () => h('div', count.value)
  }
}

 


6.子组件组件内部的方法想暴露给父组件通过ref方式去获取使用,通过expose方法即可

import {  ref } from 'vue'
 
export default {
  setup(props, { expose }) {
    const num= ref(0)
    const count = ref(0)
    const increment = () => ++count.value
    expose({
      count,
      increment
    })
  }
}
父组件: <child ref='childCom'></child>
调用:   this.$refs.childCom.increment  // 成功,可以获取到对应方法
调用:   this.$refs.childCom.count      // 成功,可以获取到对应值
调用:   this.$refs.childCom.num        // 失败,不可以获取到对应值
expose未导出的属性,父组件中调用就会是undefined,未暴露的属性父方法是拿不到的

 

posted @ 2022-12-23 20:56  Mr。Liu  阅读(506)  评论(0)    收藏  举报