vue3-setup中如何获取组件实例

7/18/2020 vue3
  • 在setup和其他CompositionAPI中没有this
  • 可通过getCurrentInstance获取当前实例
  • 如果使用OptionAPI可照常使用this
<template>

</template>


<script lang="ts">
import { onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
export default {
    name: 'GetInstance',
    data(){
        return {
            name: 'zhangsan'
        }
    },
    setup() {
        console.log('this in setup', this);    // undefined 
        onMounted(() => {
             console.log('this in onMounted', this); // undefined
             console.log('x 2 onMounted', instance.data.name);  // zhangsan
        })
        const instance = getCurrentInstance() as ComponentInternalInstance
        console.log('instance', instance);
        console.log('x 1', instance.data.name); // undefined
    },
    mounted() {
        console.log('this in mounted', this);
        console.log('this in mounted name', this.name);
    },


}
</script>

<style>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
更新: 7/25/2022, 3:15:19 PM