[英]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.