首先,了解我的问题和选择:我正在将现有的 JS 元素转换为 Vue.js 框架。
我正在努力解决一个在 jQuery 中很容易解决但在 Vue.js 中让我头疼的问题
在我的代码中,我必须在加载整个页面后生成 Canvas ,然后将它们添加到 Canvas 容器 div。单击按钮时,我需要更改所有这些 Canvas 的 CSS。 Canvas 现已使用 document.createElement('canvas')
添加.
Vue 的方式是添加一个 v-bind:style
属性到 Canvas 并通过在 data()
中设置变量来更改它vue JS 代码,像这样:<canvas v-bind:style="{width: customWidth}></canvas>"
和 <button v-on:click="customWidth++">+</button>
.
到目前为止我的理解是,如果我添加 v-bind:style
以下列方式生成 Canvas 时的属性: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
}
}
响应按钮
最佳答案
vue'ify 整个事情并使用 v-for
创建 Canvas 将是理想的,但如果这是一个问题,只需使用纯 JS
document.querySelector('#canvas-container canvas')
并以这种方式添加样式。
关于javascript - 添加 Vue.js v-bind :style attribute to an element that is dynamically created after page load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269765/