簡體   English   中英

vuejs - 動態添加的 dom 元素未呈現

[英]vuejs - dynamic added dom element not rendered

我在mounted后添加了一系列div

  mounted(){
   // let self = this

    let connect = document.querySelector('.connect')
    let h2 = 97.5;

    connect.setAttribute('style','width:60px; height:'+h+'px')

    var i;
    for(i = 0 ; i < 8 ; i++ ){
      let linker_node = document.createElement('div')
      linker_node.setAttribute('style','width:60px; height:'+ h2 +'px')
      i%2 ? linker_node.setAttribute('class','linker toplink'):linker_node.setAttribute('class','linker bottomlink')
      connect.appendChild(linker_node)
    }

和我的css

  .toplink{
    background:#fff;
  }
  .bottomlink{
    background:grey;
  }

最后我會得到html

<div data-v-57e2cc88="" class="connect" style="width:60px; height:780px">
    <div class="linker bottomlink" style="width:60px; height:97.5px"></div>
    <div class="linker toplink" style="width:60px; height:97.5px"></div>
    <div class="linker bottomlink" style="width:60px; height:97.5px"></div>
    <div class="linker toplink" style="width:60px; height:97.5px"></div>
    <div class="linker bottomlink" style="width:60px; height:97.5px"></div>
    <div class="linker toplink" style="width:60px; height:97.5px"></div>
    <div class="linker bottomlink" style="width:60px; height:97.5px"></div>
    <div class="linker toplink" style="width:60px; height:97.5px"></div>
</div>

但是 css background沒有渲染。 我檢查chrome inspect

在此處輸入圖像描述

如圖所示,class toplink / bottomlink根本沒有出現。

我相信這與vue生命周期鈎子有關,但不確定如何調試它。

我該如何解決這個問題?

您的代碼似乎工作正常:

 new Vue({ el: "#app", mounted() { // let self = this let connect = document.querySelector('.connect') let h2 = 97.5; connect.setAttribute('style', 'width:60px; height:' + h2 + 'px') var i; for (i = 0; i < 8; i++) { let linker_node = document.createElement('div') linker_node.setAttribute('style', 'width:60px; height:' + h2 + 'px') i % 2? linker_node.setAttribute('class', 'linker toplink'): linker_node.setAttribute('class', 'linker bottomlink') connect.appendChild(linker_node) } } });
 .toplink { background: #fff; }.bottomlink { background: grey; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='app'> <div class='connect'> </div> </div>

我從這個鏈接找到了解決方案:

在這兩種情況下 CSS 更改都不會生效,因為您嘗試設置樣式的元素不是組件的一部分,因此沒有 data-v-xxxxxxx 屬性,該屬性用於當前 scope (組件)中的元素樣式使用。 當使用 scoped 屬性時,我們告訴 vue 僅將 css 應用於具有 data-v-xxxxxxx 的元素,而不是嵌套元素。 因此我們需要顯式地使用深度選擇器。

所以我需要在我的css 8CBA22E28EB17B5F5C6AE2A266AZ class 中使用vue-loader的深度選擇器>>>

>>>.toplink{
    background:#fff;
  }
>>>.bottomlink{
    background:grey;
  }

那么一切都會正確渲染。

暫無
暫無

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

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