Cat Fingers
Cat Fingers

Reputation: 75

How to reference child elements in a component?

I'm trying to build a parent-child tree in Vue, and I want to pass the parent's DOM/element ID down to the child so that they can append to it. Here is a simple example of what I am trying to achieve as the DOM structure in the browser:

<div id="my-id">
    <p>parent-comp header</p>
    <div id="my-id-child">
        <p id="my-id-child-content">child-comp content</p>
    </div>
    <p>parent-comp footer</p>
</div>

The only way I have been able to do this so far is to duplicate the id into another property propid and pass them both down the tree. This seems messy. See my sample code:

<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>

<parent-comp id="my-id" propid="my-id"></parent-comp>

<script type="application/javascript">
    Vue.component('parent-comp', {
        props: {
            propid: String
        },
        template: ` <div>
                        <p>parent-comp header</p><child-comp :id="propid + '-child'" :propid="propid + '-child'"></child-comp><p>parent-comp footer</p>
                    </div>`,
    });

    Vue.component('child-comp', {
        props: {
            propid: String
        },
        template: `<div>
                    <p :id="propid + '-content'">child-comp content</p>
                   </div>`,
    });

    new Vue({
        el: '#my-id'
    });
</script>
</body>
</html>

I'm guessing there must be a better way to achieve this? It seems like it should be a simple task? Thanks.

Upvotes: 2

Views: 481

Answers (1)

tony19
tony19

Reputation: 138286

There are indeed better ways to refer to specific elements within the current component's template: use refs in the template, which would allow your component script to access them via this.$refs:

<template>
  <div>
    <button ref="myBtn">Click</button>
  </div>
</template>

<script>
export default {
  methods: {
    doFoo() {
      console.log(this.$refs.myBtn)
    }
  }
}
</script>

The scope isolation is maintained. For example, when there are multiple instances of component A on a page, and one of them gets a reference to its button (via this.$refs.myBtn) to disable it, only that instance's button is disabled. All other A instances are unaffected.

Upvotes: 1

Related Questions