1

I define a plugin and use it like:

import * as d3 from "d3"
import Vue from "vue"


export default {
    install: function(){
        window.d3 = d3
        Vue.prototype.d3 = d3
    }
}

Then when I try to define a component methods using that plugin:

<script>
    export default {
        methods:{
            lineFunction: this.d3.line()
                             .x(function(d, i) { return i*10; }) 
                             .y(function(d) { return d*10; }) 
                             .curve(d3.curveMonotoneX)
            }
        }
    }
</script>

It keeps giving me

"Uncaught TypeError: Cannot read property 'line' of undefined"

it seems this.d3 is not ready, I tried use d3 rather than this.d3, both are not working, thoughts?

2 Answers 2

2

lineFunction has to actually be declared as a function, with parenthesis and braces:

export default {
    methods: {
        lineFunction () {
             return this.d3.line()
                 .x((d, i) => i * 10) 
                 .y(d => d * 10) 
                 .curve(d3.curveMonotoneX);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but the return of this.d3.line()... is a function, I try to understand why there is no d3 plugin ready
@Kuan - You can't set it directly like that, because this is not in Vue's context without it actually being a function. If you want to set the function like that, you'll have to either import d3 directly in this file, or do it in the created hook.
Thanks for the solution, although I do not understand why and how Vue treat it, but it works.
0

this, in your case, points to the Vue instance, which can be used to accesss props (defined in 'props' block), data (defined 'data' block), methods, and some others. d3 is not one of them.

To use d3, simply import it inside the <scrip> section:

<script>
    import * as d3 from "d3"
    export default {

        methods:{
            lineFunction: function() {
                 d3.line()
                             .x(function(d, i) { return i*10; }) 
                             .y(function(d) { return d*10; }) 
                             .curve(d3.curveMonotoneX)
                 }
            }
        }
    }
</script>

1 Comment

Thanks, but did u test your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.