javascript - Vue.js 从模板中分离样式

标签 javascript vue.js

我使用带有 <style> 的模板出于 CMS 原因,必须靠近其 div 的 block 。

当我运行 Vue.js 时,它似乎删除了样式 block ,说...

- 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>

最佳答案

问题

在 Vue 2 中,根实例比在 Vue 1 中更像是一个组件。

这意味着当您将 Vue 实例绑定(bind)到 #app 时,它会将 #app 中的所有内容消化为 vue 模板。这意味着标签无效,它们将从模板中删除。这就是 Vue 2 中的工作方式。

休闲

我在这里用 codepen 重现了这个问题

https://codepen.io/Fusty/pen/gqXavm?editors=1010

嵌套在 Vue 绑定(bind)到的标签中的 <style> 标签。它应该设计背景红色和文本颜色绿色。然而,我们只看到了这一点(取决于你的浏览器启动 Vue 的速度),最终 vue 删除了这些样式标签,因为它将 #app 消化为模板,然后用它认为应该存在的内容更新 DOM(没有 <style>标签)。

更好的娱乐

感谢 Vue-Land discord 上的用户@joestrouth1#6053,我们也有这个问题的分支。

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 中。可能是因为它比组件更独特地对待根实例,但我不是 100% 确定这个主题。

解决方案(Hack,不是最佳实践或特别推荐)

在 Vue 实例的 <style> 生命周期钩子(Hook)期间,created 标签仍然在 DOM 中,并且在 mounted 生命周期钩子(Hook)触发时被删除。让我们查询 #app 元素中的所有样式标签,保存它们,然后在 Vue 消化模板后将它们追加回 #app 元素。

将以下内容添加到您的根 Vue 实例将获取您的 Vue 实例绑定(bind)到的任何元素中的任何 <style> 标记(通过 el: 'someSelector' )并将它们附加(可能重新定位)到您的 Vue 实例绑定(bind)到的元素。

  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]);
  }

注意:这绝对是一种黑客行为,可能会产生我尚未遇到的意外后果,因此无法明确否认。使用风险自负。

关于javascript - Vue.js 从模板中分离样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42746964/

相关文章:

javascript - 通过在单词序列后添加新行来装饰文本

javascript - 我如何构造/访问我的非 node.js 应用程序的 react 组件?

javascript - vue - 自定义 block - 语法高亮

javascript - 使用 VueJS 进行嵌套输入的 Treeview

javascript - 此 .ejs 文件中的 else 语句显示错误 "Unexpected token else in/home/ubuntu/workspace/v1/views/home.ejs while compiling ejs"

javascript - 使用带有 unicode 字符的 ng-pattern (Angular.JS) 的不良结果

javascript - VueJS : Flush/reload the whole tree-view

javascript - 如何将文件夹导入为Vue组件

css - Vue : bind a background style for cross browsers

php - 如何知道php文件是从源代码加载的