我想从initGrid()函数中调用ctx
变量,并在drawGrid()函数中使用它,但是它不允许我使用该变量,即使我使用“this”。
<script>
export default {
data: () => ({
width: 1200,
height: 800,
squareH: 15,
squareW: 15,
squareRow: 10,
squareCol: 10,
squares: [],
}),
directives: {},
methods: {
initGrid() {
let grid = document.getElementById('grid');
var ctx = grid.getContext('2d');
},
drawGrid() {
this.ctx.fillStyle = 'black';
this.ctx.fillRect(10, 10, this.squareW, this.squareH);
}
},
mounted() {
this.initGrid();
this.drawGrid();
}
null
只需将它添加到您的数据对象中,并在两种方法中使用它:
<script>
export default {
data: () => ({
width: 1200,
height: 800,
squareH: 15,
squareW: 15,
squareRow: 10,
squareCol: 10,
squares: [],
ctx:null
}),
directives: {},
methods: {
initGrid() {
let grid = document.getElementById('grid');
this.ctx = grid.getContext('2d');
},
drawGrid() {
this.ctx.fillStyle = 'black';
this.ctx.fillRect(10, 10, this.squareW, this.squareH);
}
},
mounted() {
this.initGrid();
this.drawGrid();
}
您需要授予组件对数据的访问权限。 当您在init网格中执行var ctx=grid.getcontext('2D');
时,网格和ctx将在那里创建,但您不会告诉vue或此组件它应该“拥有”或将状态与其关联。 您可以通过使用ctx信息实际初始化组件的数据来解决这个问题。
null
<script>
export default {
data: () => ({
width: 1200,
height: 800,
squareH: 15,
squareW: 15,
squareRow: 10,
squareCol: 10,
squares: [],
ctx: null,
// Note how we add ctx to the data here.
}),
directives: {},
methods: {
initGrid() {
let grid = document.getElementById('grid');
// Now this.ctx is defined and can be used
this.ctx = grid.getContext('2d');
},
drawGrid() {
this.ctx.fillStyle = 'black';
this.ctx.fillRect(10, 10, this.squareW, this.squareH);
}
},
mounted() {
this.initGrid();
this.drawGrid();
}