Is it possible to get the assigned ref name in a component? Vue.js

Viewed 2493

I created a new component that will render a chart using Chart.js. I would like to access this component via a reference.

<kpis-linechart name="inv-speed" ref="inv-speed-chart" :information="team.invoice_details">

A chart with chart.js is created using <canvas id="chart-id"></canvas> in the html.

I would like assign the chart id the same value as the ref value.

Is there a way to get the ref. name from the component ?

Example : this.$ref_name

This is my code so far :

Vue.component('kpis-linechart',{

    template : '#kpis-linechart-template',

    props : {
        information : Object,
        name : String
    },
    // I WANT TO REPLACE THIS CODE IN ORDER TO GET THE REF NAME AS ID //
    // I WANT TO REPLACE THIS CODE IN ORDER TO GET THE REF NAME AS ID //
    computed : {
        id_chart(){
            return this.name + '-chart'
        }
    },


    methods : {
        updateChart(){
            this.chart = new Chart(document.getElementById(this.id_chart),{
                type : 'line',
                data : {
                    labels : ['hola','como','estas'],
                    datasets : [
                        {
                            label : 'Queso',
                            data : [1,2,4]
                        }
                    ]

                    
                }
            })
        }
    },

    mounted(){
        this.updateChart()
        console.log('CREATING CHART')
        // console.log(this.information)
        console.log(this)
    }

})
1 Answers

The best way would be to add a that name as a prop (as ref is not passed as a prop):

<my-component ref="something" name="something" />

If you don't want this, you can loop through the parent's $refs and check which one refers to this. But... this is only available when the component is already mounted, so it cannot be a computed.

Demo:

Vue.component('kpis-linechart', {
  template: '#kpis-linechart-template',
  data() {
    return {
      id_chart: 'default-id'
    };
  },
  mounted() {
    const entry = Object.entries(this.$parent.$refs)
                        .find(([key, value]) => value === this);
    if (entry) {
      this.id_chart = entry[0];
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <kpis-linechart ref="something"></kpis-linechart>
</div>

<template id="kpis-linechart-template">
  <p :id="id_chart">I'm a chart, and my id is "<b>{{id_chart}}</b>"</p>
</template>

Related