我使用一个带有<style>块的模板,出于的原因,该模板必须位于其div附近。
当我运行Vue.js时,它似乎删除了样式块,说.
- Templates should only be responsible for mapping the state to the UI.
Avoid placing tags with side-effects in your templates, such as <style>,
as they will not be parsed.我能做什么?
var app = new Vue({
el: '#app'
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.0/vue.js"></script>
<div id="app">
<style>
#div_123 {
background: http://placehold.it/850x150;
}
@media screen and (max-width: 640px) {
#div_123 {
background: http://placehold.it/350x150;
}
}
</style>
<div id="div_123">
Test
</div>
</div>
发布于 2017-06-16 09:21:45
这适用于我的特定情况,我允许用户存储一个CSS字符串,然后我需要在特定的页面上呈现它- ei:预览页面。
这里的上下文是css作为字符串保存在数据库中,并在Vue组件中获取和呈现。
# html
<html>
<head>
<style id="app_style"></style>
</head>
<body>
<div id="app"></div>
</body>
</html># app.vue
data() {
return {
dynamic_css: ''
}
},
created() {
// fetch css from database, set as `this.dynamic_css`
},
watch {
dynamic_css: function(newValue) {
document.getElementById('app_style').innerHTML = newValue
}
}发布于 2019-02-06 17:56:56
问题
在Vue 2中,与Vue 1相比,根实例更像一个组件。
这意味着当您将Vue实例绑定到#app时,它将#app中的所有内容作为vue模板进行消化。这意味着标签无效,它们将从模板中删除。这就是Vue 2的工作方式。
娱乐
我在这里用代码重现了这个问题
https://codepen.io/Fusty/pen/gqXavm?editors=1010
嵌套在标记Vue中的<style>标记绑定到。它的风格应该是背景红色和文字颜色绿色。但是,我们只看到其中的一闪而过(取决于浏览器启动vue的速度),最终vue在将#app作为模板摘要时删除这些样式标记,然后用它认为应该存在的内容更新DOM (没有<style>标记)。
更好的娱乐
感谢用户@joestrouth1#6053在Vue-Land的不和谐,我们也有这个叉子我的娱乐问题。
https://codepen.io/joestrouth1/pen/WPXrbg?editors=1011
看看控制台。上面写着。。。
"[Vue warn]: Error compiling template:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <style>, as they will not be parsed.
1 | <div>
2 | <style>
| ^^^^^^^
... etc ...抱怨模板中的样式标记。
这是针对实际问题的。值得注意的是,在Vue 1中没有出现这种情况,这可能是因为它比组件更独特地对待根实例,但在这个主题上我不能百分之百肯定。
解决方案(Hack,不是最佳实践或特别推荐的)
<style>标记在Vue实例的created生命周期钩子期间仍然在DOM中,并且在mounted生命周期钩子触发时被删除。让我们只查询#app元素中的所有样式标记,保存它们,然后在Vue消化模板之后将它们追加到#app元素中。
将以下内容添加到根Vue实例中,将在Vue实例绑定到的任何元素(通过<style> )中接受任何el: 'someSelector'标记,并将它们(可能将它们重新定位)附加到绑定到Vue实例的元素中。
created: function() {
this.styleTagNodeList = document.querySelector(this.$options.el).querySelectorAll('style');
},
mounted: function() {
for(var i = 0; i < this.styleTagNodeList.length; ++i)
this.$el.appendChild(this.styleTagNodeList[i]);
}注意:这绝对是一次黑客攻击,可能会有意想不到的后果,我还没有遇到,也不能明确地否认。用你自己的风险。
https://stackoverflow.com/questions/42746964
复制相似问题