使用包vue-property-decorator
。
组件内容:
<template>
<div>
<label ref="label">asd</label>
</div>
</template>
<script lang="ts">
class Someclass extends Vue {
public $refs!: {
label: HTMLElement
}
private mounted(): void {
console.log(this.$refs.label) // returns a Vue component, instead of just html
}
}
</script>
这可能是因为 this
指向了一个类本身。但是,如何访问 this.$refs.label
?
最佳答案
如果你在 Vue 组件上放置一个 ref
,它的 DOM 元素可以像这样访问:
this.$refs.label.$el
this.$refs.label
是一个 Vue 实例及其 API is described here .
关于 ref 属性:
ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element; if used on a child component, the reference will be component instance.
更新
确实,您的示例使用的是标签元素,而不是组件。我假设您没有在问题中显示整个代码并引用了文档的相关部分。正如您在下面看到的,您的代码没有输出您所说的内容。
Vue.component('my-component', {
template: '<div><label ref="label">asd</label></div>',
mounted() {
const ref = this.$refs.label;
console.log(ref);
console.log("typeof(ref): " + typeof(ref));
console.log("Is component: " + (ref instanceof Vue));
console.log("Is HTMLElement: " + (ref instanceof HTMLElement));
}
})
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component />
</div>
关于javascript - this.$refs 指向类样式组件中的一个 vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766025/