繁体   English   中英

如何从对象内部访问vuejs方法? (Vuejs 2)

[英]How to access vuejs method from inside an object ? (Vuejs 2 )

我想从Chart对象访问getValue方法,但函数未定义。

<template>
    <div>
        <canvas width="600" height="400" ref="canvas"></canvas>
    </div>
</template>
<script>
    import Vue from 'vue';
    import Chart from 'chart.js';
    import Axios from 'axios';

    export default {
        mixins: [DateRangeMixin],
        props: {
          // other props...
            callback: false,
        },

        data() {
            return {
                chart: '',
            };
        },

        mounted() {
       // ...
        },

        methods: {

      //other methods...,
               getValue(data) {
                    if (data === 1) {
                        return 'Up'
                    } else if(data === 0) {
                        return 'Down';
                    }
                },
            render(data) {
                this.chart = new Chart(this.$refs.canvas, {
                    type: 'line',
                    data: {

                        labels: Object.keys(data),
                        datasets: [{
                           // a lot of data ....                   
                            data: Object.values(data),

                        }]

                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true,
                                    callback(label, index, labels) {
                                        return this.getValue(label); // <-- Tried this and got: 'this.getValue is not a function'. I understand it bounces to new Chart object, but how to resolve this?
                                    }
                                }
                            }]
                        }
                    }

                });

            },
        },
    };
</script>

据我所知,这是因为图是一个对象, this指向它,但我要如何解决这一点,从回调访问我的方法是什么?

我想如果将export default ...设置为variable ,则可以通过variable.methods.getValue访问我的方法,但是在这种情况下,如何实现我的目标?

在创建new Chart()将其分配给变量self: var self = this; 然后,您可以通过self访问您的组件属性。

暂无
暂无

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

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