setup参数及细节问题

1. setup在beforeCreate生命周期回调之前就执行了,而且就执行一次
 
<template>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
   name: 'childSetup',
   beforeCreate(){
       console.log('已执行beforeCreate');
   },
    console.log('已执行setup');
       return{     
       }
   }
});
</script>

由此推断出:setup执行的时候,当前组件还没有被创建出来,也就是说组件实例对象的this根本没法用

不能用this去调用data/components/methods/props

2. setup参数:setup(props,context){}

        // props:对象,里面有父组件向子组件传递的数据,并且是在子组件中使用props接收到的所有属性
        //      包含props配置声明且传入了的所有属性的对象
        // context参数:对象,包含attrs对象(获取当前组件标签上的所有属性的对象),emit方法(分发事件),slot对象(插槽)
        //                      包含没有在props配置中声明的属性对象,相当于this.$attrs
父组件:
<template>

<!--给子组件自定义事件xxx--> <childSetup @xxx="clikXX"></childSetup> </template> <script lang='ts'> import { defineComponent,ref } from 'vue'; import childSetup from './setup2.vue' export default defineComponent({ name:'setUp', components:{ childSetup }, setup(){ function clikXX(){ console.log('父组件中方法'); } return { clikXX } } }); </script>

子组件:

<template>
<h2>setup子组件</h2>
<button @click="emitXx">点击触发父组件方法</button>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
   name: 'childSetup',
   setup(props,context){
       function emitXx(){
          // 调用父组件方法,用context.emit去触发
           context.emit('xxx')
       }
       return{
            emitXx
       }
   }
});
</script>

 

posted @ 2022-05-02 14:02  幻影之舞  阅读(419)  评论(0)    收藏  举报