VueJ在组件中获取元素


115

我有一个组件,如何选择其元素之一?

我正在尝试获取此组件模板内的输入。

可能有多个组件,所以queryselector必须仅解析该组件的当前实例。

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

   ...

    created: function() {
        somevariablehere.querySelector('input').focus();
    }
});

提前致谢

Answers:


109

您可以使用来访问vuejs组件的子代this.$children。如果要在当前组件实例上使用查询选择器,则this.$el.querySelector(...)

仅做简单的操作即可console.log(this)向您展示vue组件实例的所有属性。

另外,如果您知道要在组件中访问的元素,则可以向其添加v-el:uniquename指令并通过以下方式访问它this.$els.uniquename


6
提示:this.$el在安装之前是不确定的。如果您想初始化变量,请在mount()
wedi 18'Jul 10'9

165

vuejs 2

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


1
这使我意识到该ref属性可用于任何HTML元素或Vue组件。好东西。
C. Bess

3
看起来像this。$ refs.uniqueName是一个数组,因此需要this。$ refs.uniqueName [0]来获取引用的元素。
Nicolas S.Xu

:只有安装组件,它可以在父母的安装方法完成后medium.com/@brockreece/...
约尔丹Georgiev的

45

答案不清楚:

使用this.$refs.someName,但是要使用它,必须添加ref="someName"parent

请参阅下面的演示。

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-forthis.$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>


1
同样重要的是要注意,退回的物品没有反应性。
Pithikos

38

请注意,在Vue2中,仅在安装组件后才能访问this。$ refs.uniqueName


2
安装在Vue生命周期中的所有内容都不会在您的浏览器中显示。由于尚未安装,因此没有可用的DOM检查。
Coreus


1

合成API

模板引用部分介绍了如何进行统一:

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

该引用从安装开始便带有DOM元素。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.