【问题标题】:How to access instance in vue3 composition API lifecycle hooks如何在 vue3 组合 API 生命周期钩子中访问实例
【发布时间】:2023-01-13 00:54:30
【问题描述】:
在将我的代码重构为组合 API 时,我遇到了一个完全出乎意料的问题:似乎没有任何(已记录的)方法可以从生命周期挂钩访问当前实例。
示例代码:
import { defineComponent, onMounted } from 'vue';
export default defineComponent({
setup() {
onMounted(() => {
console.log(this); // <-- will be undefined
});
},
mounted() {
console.log(this); // <-- will be the component
},
}
我花了几个小时试图找到解决方案,最终只是使用旧的选项 API 来获得我想要的东西。我读过的所有示例、教程或文档都没有在挂钩中使用this。
但我觉得难以置信,只有未记录的getCurrentInstance 才是从钩子中获取当前实例的方法。
那么,我错过了哪个医生?
【问题讨论】:
标签:
vuejs3
vue-composition-api
【解决方案1】:
你在组件中需要this干什么?
如果您使用 Composition API 创建您的组件,那么您可以直接访问所有属性,而无需使用 this。
这是一个非常基本的例子:
const { createApp, ref, onMounted } = Vue;
const App = {
setup() {
const count = ref(0);
const up = function() {
count.value++;
}
onMounted(() => {
count.value = 10
});
return {count, up, }
}
}
const app = createApp(App)
app.mount('#app')
<div id="app">
{{count}}
<button type="button" @click="up()">+1</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>