Vue.js separates styles from a template

I use a template with a block <style>that should be next to its div for CMS reasons.

When I run Vue.js, it seems like it removes the style block, saying ...

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

What can I do?

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>
Run codeHide result
+5
source share
2 answers

This works for my situation where I allow users to store a CSS string and then I need to display it on specific pages.

# 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);
},
+1
source

Problem

In Vue 2, the root instance is treated more as a component than in Vue 1.

, Vue #app, #app vue. , , . Vue 2.

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

<style> Vue, . , - . , ( , 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. , , , 100% .

(, )

<style> DOM created Vue mounted . #app, , #app , Vue .

Vue <style> , Vue ( 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]);
  }

: , , , , . .

+1

Source: https://habr.com/ru/post/1672090/


All Articles