核心:
- 在setup和其他Composition API中没有this
- **可通过getCurrentInstance获取当前实例 **
- Options API中照样可以使用this
上代码:
<template>
<div>
<h1>获取实例</h1>
<p>在组合式API中,可以通过`getCurrentInstance`方法获取当前组件实例</p>
<p>在组合式API中,可以通过`getCurrentInstance`方法获取当前组件实例</p>
</div>
</template>
<script>
import { getCurrentInstance, onMounted } from 'vue'
export default {
data() {
return {
msg: 'hello world'
}
},
// setup式beforeMount和onMounted的合集,所以在这里打印instance.data.msg为undefined
setup() {
const instance = getCurrentInstance();
onMounted(() => {
console.log(instance);
console.log(instance.data.msg); // hello world
})
console.log(instance.data.msg) // undefined
}
}
</script>
<style scoped>
</style>