Vue.js 中如何获取组件实例
在 Vue.js 中,可以通过 'ref' 属性来获得组件的实例。
首先,在组件的模板中,使用 'ref' 属性来给组件命名,如下所示:
<template>
<div>
<my-component ref='myComponent'></my-component>
</div>
</template>
然后,在组件的 JavaScript 代码中,可以通过 'this.$refs' 来访问组件的实例,如下所示:
<script>
export default {
mounted() {
const myComponentInstance = this.$refs.myComponent;
// 使用 myComponentInstance 来操作组件的方法和属性
}
}
</script>
在 'mounted' 生命周期钩子中,可以确保组件已经被渲染并且可以访问到组件的实例。
原文地址: http://www.cveoy.top/t/topic/bneq 著作权归作者所有。请勿转载和采集!