0đź‘Ť
One can set the prototype property, just as you are doing, before creating the Vue instances (as is described in Adding Instance Properties).
As is described in this answer, arrow functions don’t bind to this
, so make sure you use non-arrow functions.
Don’t use arrow functions on an instance property or callback (e.g.
vm.$watch('a', newVal => this.myMethod())
). As arrow functions are bound to the parent context,this
will not be the Vue instance as you’d expect andthis.myMethod
will beundefined
.
1
See an example of this in the snippet below. Click the draw button to draw a line on the canvas.
//wait for DOM to load
document.addEventListener('DOMContentLoaded', function() {
//set property on all Vue instances
Vue.prototype.$c = document.getElementById('myCanvas').getContext('2d');
//create Vue instance
var vm = new Vue({
el: '#example',
methods: {
draw: function() {
this.$c.beginPath();
this.$c.moveTo(100, 100);
this.$c.lineTo(200, 200);
this.$c.stroke();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<canvas id="myCanvas"></canvas>
<div id="example">
<button @click="draw">draw</button>
</div>
1https://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods
Source:stackexchange.com