【发布时间】:2017-11-13 17:05:33
【问题描述】:
首先要了解我的问题和选择:我正在将一个现有的 JS 项目翻译成 Vue.js 框架。
我正在努力解决一个在 jQuery 中很容易解决但在 Vue.js 中让我头疼的问题
在我的代码中,我必须在加载整个页面后生成画布,然后将它们添加到画布容器 div。单击按钮时,我需要更改所有这些画布的 CSS。画布现在使用document.createElement('canvas') 添加。
Vue 的方法是在画布上添加一个v-bind:style 属性并通过在data() vue JS 代码中设置一个变量来更改它,如下所示:<canvas v-bind:style="{width: customWidth}></canvas>" 和<button v-on:click="customWidth++">+</button>。
到目前为止我的理解是,如果我添加 v-bind:style 属性同时以下列方式生成画布:canvas.setAttribute('v-bind:style', '{width: customWidth}'),Vue.js 将不会知道它的存在,因为它是在加载后生成的页面。
我正在寻找有关如何解决我的问题的建议。
所以,为了说明,这个:
<div id="canvas-container"><div>
<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>
应该变成这样:
<div id="canvas-container">
<canvas v-bind:style="{width: customWidth}"></canvas>
<canvas v-bind:style="{width: customWidth}"></canvas>
<canvas v-bind:style="{width: customWidth}"></canvas>
<canvas v-bind:style="{width: customWidth}"></canvas>
<canvas v-bind:style="{width: customWidth}"></canvas>
<div>
<button v-on:click="customWidth++">+</button>
<button v-on:click="customWidth--">-</button>
在 Vue JS 代码中使用这个:
data(){
return{
customWidth: 100
}
}
并响应按钮
【问题讨论】:
-
是什么决定了容器中有多少画布?使用
v-for对其进行迭代。 -
我同意 Bert,vue'ify 整个事情并使用
v-for创建画布。如果这是一个问题,只需使用纯 JSdocument.querySelector('#canvas-container canvas')并以这种方式添加样式。 -
@webnoob 这对我有用,感谢您为我指明方向。我同意 Vueify 整个事情更正确,但这是一个很好的临时解决方案!
-
@fluffypirate 够公平的 - 如果我们有所有的时间在世界上吧? :) 我已经为你添加了答案。
标签: javascript css canvas vue.js