javascript - this.$refs 指向类样式组件中的一个 vue 组件

标签 javascript typescript vue.js

使用包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/

相关文章:

javascript - 使用 onDisconnect() 拒绝 Firestore/Firebase 权限

javascript - 切换网站语言 JS/JSON

vue.js - 具有相同名称函数的两个 Mixin Vuejs

javascript - 如何提交表单而不重定向到其操作页面?

javascript - TypeScript 编译后 : Uncaught SyntaxError: Unexpected token {

Angular 4 向控制台打印消息

javascript - 在 typescript 中将 React.Component 状态设置为等于 this.props 值是否存在问题?

javascript - 在一页中堆叠 vuetify 元素

javascript - 在vue js中点击更新两个分页组件

javascript - AngularJs 和 Bluemix QA API 无法发出发布请求