2017-07-07 73 views
0

我使用VueJS,我想将HTML-CanvasCanvas-Context合并。我想打电话从context内我components像:VueJS + Canvas-Context如何链接在一起?

mounted() { 
    this.$c.moveTo(100, 100) 
    this.$c.lineTo(200, 200) 
} 

我在main.js开始:

Vue.prototype.$c = document.querySelector('canvas').getContext('2d') 

而且,我也不知道如何与关键字this工作在构建这样的:

const Something = (x, y) => { 
    this.x = x 
    this.y = y 
    this.draw() { 
    this.$c.moveTo(100, 100) 
    this.$c.lineTo(200, 200) 
    } 
} 

所以,我怎么能结合canvas-contextVueJS

回答

0

在创建Vue实例(如Adding Instance Properties中所述)之前,可以像您一样设置原型属性。

this answer中所述,箭头函数不会绑定到this,因此请确保使用非箭头函数。

请勿在实例属性或回调(例如vm.$watch('a', newVal => this.myMethod()))上使用arrow functions。由于箭头函数绑定到父上下文,因此this将不是您所期望的Vue实例,而this.myMethod将是undefined1

参见下面的代码段的一个例子。点击绘制按钮在画布上绘制一条线。

//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>


https://vuejs.org/v2/guide/instance.html#Properties-and-Methods