簡體   English   中英

向頁面加載后動態創建的元素添加Vue.js v-bind:style屬性

[英]Adding a Vue.js v-bind:style attribute to an element that is dynamically created after page load

首先,要了解我的問題和選擇:我正在將現有的JS項目轉換為Vue.js框架。

我正在努力解決一個易於在jQuery中解決但在Vue.js中傷腦筋的問題

在我的代碼中,我必須在加載整個頁面后生成畫布,然后將它們添加到畫布容器div中。 當我單擊一個按鈕時,需要對所有這些畫布的CSS進行更改。 截至目前,使用document.createElement('canvas')添加了document.createElement('canvas')

Vue的方法是向畫布添加v-bind:style屬性,並通過在vue JS代碼的data()設置變量來更改它,如下所示: <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
   }
}

並響應按鈕

vue'ify整個事情,並使用v-for創建畫布將是理想的,但是如果這是一個問題,只需使用純JS

document.querySelector('#canvas-container canvas') 

並以這種方式添加樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM