Vue.js从模板中分离样式

时间:2017-03-12 11:42:18

标签: javascript vue.js

出于CMS原因,我使用带有<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.

我该怎么办?

&#13;
&#13;
var app = new Vue({
  el: '#app'
});
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

问题

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

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

娱乐

我在这里用codepen重新创建了问题

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

绑定到标签Vue中的<style>标签已绑定。它应该将背景设置为红色,文本设置为绿色。但是,我们只看到其中的一瞬(取决于浏览器启动Vue的速度),最终vue在将#app消化为模板时会删除这些样式标签,然后使用其认为应该存在的DOM更新DOM(不带{ {1}}标签)。

更好的娱乐方式

感谢Vue-Land不和谐用户@ joestrouth1#6053,我们也很高兴看到这个问题。

https://codepen.io/joestrouth1/pen/WPXrbg?editors=1011

检出控制台。它读。 。

<style>

抱怨模板中的样式标签。

这是针对实际问题的信息。值得一提的是,在Vue 1中不会发生这种情况。可能是因为它比组件更独特地对待根实例,但是我对此主题不是100%肯定。

解决方案(缺乏经验,不是最佳实践或不建议这样做)

"[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实例的<style>生命周期钩子期间仍位于DOM中,并且在created生命周期钩子触发时被删除。让我们只查询#app元素内的所有样式标签,保存它们,然后在Vue消化模板后将它们附加回#app元素。

将以下内容添加到您的根Vue实例中,将在您的Vue实例绑定到的任何元素中(通过mounted)使用任何<style>标签,并将它们附加(可能将它们重新定位)到您的Vue元素实例绑定到。

el: 'someSelector'

注意:这绝对是一种骇客,很可能会带来意想不到的后果,而我尚未遇到过,因此无法明确声明。自行承担风险。

答案 1 :(得分:1)

这适用于我允许用户存储CSS字符串然后我需要在特定页面上呈现它的情况。

# html
<html>
  <head>
    <style id="app_style"></style>
  </head>
  <body>

    <div id="app"></div>

  </body>


# app.vue

// vue stuff

mounted(){
  $('#app_style').text(""); // clear old css
  $('#app_style').text(dynamic_css);
},