Js 获取组件中的元素

我有一个组件,如何选择它的一个元素?

我尝试获取这个组件模板中的输入。

可能有多个组件,因此 querySelector必须只解析组件的当前实例。

Vue.component('somecomponent', {
template: '#somecomponent',
props: [...],


...


created: function() {
somevariablehere.querySelector('input').focus();
}
});
210867 次浏览

有几个选项取决于你想访问的内容:

  • 您可以使用 this.$children访问 Vue.js 组件的子组件

  • 您可以使用 ref="uniqueName"在模板中标记特定的 DOM 元素,并在以后通过 this.$refs.uniqueName引用这些元素
    (但请记住,在组件/应用程序具有 安装完毕并执行初始呈现之前,您不能引用这些内容)

  • 如果无法标记元素,可以通过 this.$el.querySelector('.myClass > .childElement')使用 CSS 选择器查询子元素的 DOM
    (如上所述,组件/应用程序需要有 安装完毕)

您还可以通过在组件内部执行一个简单的 console.log(this)来进行探索,它将向您显示 Vue 组件实例的所有属性。

Vuejs 2

v-el:el:uniquename已被 ref="uniqueName"取代。然后通过 this.$refs.uniqueName访问元素。

Vue2中,请注意只有在安装组件之后才能访问 This. $refs.uniqueName

答案并不明确:

使用 this.$refs.someName,但是,为了使用它,必须使用 在父级中添加 ref="someName"

请看下面的演示。

new Vue({
el: '#app',
mounted: function() {
var childSpanClassAttr = this.$refs.someName.getAttribute('class');
    

console.log('<span> was declared with "class" attr -->', childSpanClassAttr);
}
})
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>


<div id="app">
Parent.
<span ref="someName" class="abc jkl xyz">Child Span</span>
</div>

$refsv-for

请注意,当与 v-for一起使用时,this.$refs.someName将是一个数组:

new Vue({
el: '#app',
data: {
ages: [11, 22, 33]
},
mounted: function() {
console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);
console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);
console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);
}
})
span { display: inline-block; border: 1px solid red; }
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>


<div id="app">
Parent.
<div v-for="age in ages">
<span ref="mySpan">Age is \{\{ age }}</span>
</div>
</div>

Vue 2. x

官方资料:

Https://v2.vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

一个简单的例子:

在任何元素上,都必须添加一个具有 独一无二的价值的属性 ref

<input ref="foo" type="text" >

使用 this.$refs.foo来定位该元素

this.$refs.foo.focus(); // it will focus the input having ref="foo"

组合 API

模板参考文献 部分说明了这是如何统一的:

  • 在模板中,使用 ref="myEl"; :ref=v-for
  • 在脚本中,有一个 const myEl = ref(null)并从 setup公开它

该参考从安装开始携带 DOM 元素。