vue3 setup详解

setup组合式api,新增生命周期钩子,在onBeforeMount之前。
同时删除 beforeCreate created。
setup接收两个参数 props 和 context

 setup(props, context) {
    
    

    const {
    
    attrs, slots, emit, expose} = context //非响应式可以解构                                              					  // 如果式响应式用 toRefs解构
    console.log(attrs.msg)    //非响应式对象,等同于 $attrs                  
    console.log(slots) //非响应式对象,等同于 $slots
    console.log(emit)  //$emit 触发事件
    console.log(expose) // 暴露公共属性或者函数(主要向父组件暴露)
    const test = ref(0)
    expose({
    
       // 暴露给父组件一个方法或者属性
        demo(){
    
     // 如果父组件想要使用该函数,用ref获取子组件的元素。在
        		//该元素身上有该属性。
            console.log('111111111')
        },
        test
    })
    return {
    
    
      test,
      add(){
    
    
        test.value += 1
      }
    }

  },

猜你喜欢

转载自blog.csdn.net/qq_46433453/article/details/124782859