vue2获取组件实例是个很简单的事
只需要一个this
但在vue3的composition api 把逻辑归结在了setup中
在setup中是取不到this的
那么我们需要getCurrentInstance
<template>
<div id="app">
</div>
</template>
<script>
import { getCurrentInstance } from "vue";
export default {
name: 'App',
data() {
return {
x: 1,
y: 0
}
},
setup(){
console.log(getCurrentInstance());
}
}
</script>
<style>
</style>
很明显我们打印出了这个实例中的值data 但你在这里直接去data的值是拿不到的
因为setup中获取不到data的数据
但这个只是个执行顺序的问题 我们换一个生命周期就好了
<template>
<div id="app">
</div>
</template>
<script>
import { getCurrentInstance ,onMounted } from "vue";
export default {
name: 'App',
data() {
return {
x: 1,
y: 0
}
},
setup(){
const dint = getCurrentInstance();
onMounted(()=>{
console.log(dint.data.x);
})
}
}
</script>
<style>
</style>
这样我们就成功打印出了data中的x属性
简单说 setup中通过函数getCurrentInstance获取组件实例