1
votes

I have a simple vue component, what I try is to get the DOM element from the template. 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:

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

Now the console.log in mounted() returns undefined.

1

1 Answers

2
votes

Vue requires you to have one top level element, so you need to wrap the whole thing in a div:

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

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