简体   繁体   中英

Bind plotly on click to vue.js data

I am creating project with vue.js and plot.ly javascript graph library. How can I bind in " pts " to vue's data's " TestSentences "? Here is my code, thank you to everyone who contributed My goal is to create an interactive dashboard using this variable. In this way, I can change the data by clicking anywhere on the chart.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<div id="app">
    <div id="grafik"></div>
</div>

<!-- Vue-->
<script>
    var app = new Vue({
        el: '#app',
        data: {
            TestSentences: "",
        },
        methods: {
            grafikCiz() {
                var trace1 = {
                    x: [1, 2, 3],
                    y: ["book", "pencil", "bag"],
                    mode: 'markers',
                    marker: {
                        color: ['#6886c5', '#f40552', '#1b1b2f'],
                        size: [10, 20, 30]
                    }
                };

                var data = [trace1];
                var layout = {
                    height: 400,
                    width: 400,
                };

                Plotly.newPlot('grafik', data, layout);
            },
        },
        mounted: function () {
            this.grafikCiz();
        },
    });
</script>
<!-- Vue -->

<script>
    var my_graph = document.getElementById('grafik');
    my_graph.on('plotly_click', function (data) {

        for (var i = 0; i < data.points.length; i++) {
            pts = 'x = ' + data.points[i].x + '\ny = ' + data.points[i].y + '\n\n';
        };

        alert('Closest point clicked:\n\n' + pts);

    });
</script>

Use plolty wrapper for vue.js https://github.com/David-Desmaisons/vue-plotly

You can add ref to the component

<vue-plotly v-show="display" :data="graphData" :layout="calculatedLayoutSizes" id="3dPlot"
        :display-mode-bar="false" ref="crazyPlotly"></vue-plotly>

then use the ref within your mount point or similar method

this.$refs.crazyPlotly.$on('click', d => {
                                         console.log(d);
                                         });

"d" is an obj with values like x and y datapoint, index...etc

source: https://github.com/statnett/vue-plotly/issues/23

As Alagappan A already pointed out, https://github.com/David-Desmaisons/vue-plotly can make working with plotly in javascript much easier. For me it was sufficient to just:

<vue-plotly :data="data" :layout="layout" @click="temp"> </vue-plotly>

which can directly be utilized in a method:

methods: {
  temp (value) {
    console.log(value)
  }
}
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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