javascript - 添加 Vue.js v-bind :style attribute to an element that is dynamically created after page load

标签 javascript css canvas vue.js

首先,了解我的问题和选择:我正在将现有的 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/

相关文章:

javascript - 最佳像素绘制速度?

delphi - 如何在 Delphi 中在 FMX Canvas 上画一条线

javascript - 是否可以让变量可见 "only to modules"及其扩展名?

javascript - 我想在 codeigniter 中使用 AJAX 重定向 Controller

javascript - 如何将 CustomMarker 与 MarkerClustererPlus 一起使用?

css - 使用 Polymer 1.0 在 CSS 中提升

html - 在 HTML 页面的另一个链接项中创建链接

javascript - 在 HTML5 canvas 中,translate() 和 moveTo() javascript 函数有什么区别?

javascript - 在函数警报 javascript 上添加图像

javascript - JS跨浏览器将 '$'字符替换为double '$$'字符的解决方案