简体   繁体   English

VueJS模板引用未定义多个div?

[英]VueJS template ref undefined with multiple divs?

I have a simple vue component, what I try is to get the DOM element from the template. 我有一个简单的vue组件,我尝试从模板中获取DOM元素。 Here is the component, which WORKS fine: 这是组件,可以正常工作:

<template>
        <div ref="cool">COOL!</div>
</template>

<script>
    export default {
        data() {
            return {
                blabla: 1
            }
        },
        mounted() {
            console.log("MOUNTED:");
            var cool = this.$refs.cool;
            console.log(cool);  //works!
        }
    }
</script>

And now the strange thing : I add another element to my template, doesn't matter which one..eg. 现在奇怪的是 :我在模板中添加了另一个元素,与哪个元素无关。 a new div: 新的div:

<template>
        <div ref="cool">COOL!</div>
        <div>I am new</div>
</template>

Now the console.log in mounted() returns undefined. 现在,Mounted()中的console.log返回未定义。

Vue requires you to have one top level element, so you need to wrap the whole thing in a div : Vue要求您具有一个顶级元素,因此您需要将整个内容包装在div

<template>
  <div>
    <div ref="cool">COOL!</div>
     <div>I am new</div>
  </div>
</template>

Here's the JSFiddle: https://jsfiddle.net/nrtkr6cL/ 这是JSFiddle: https ://jsfiddle.net/nrtkr6cL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM