Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - Use style tags inside vuejs template and update from data model

I would like to dynamically update styles inside style tags.

However creating a container model for Vue, removes the style tags. I know style tags should belong in the head of the page, but this is just for the sake of ease of use.

So what I would like to have is a wrapper with an element and style tags inside:

<div class="setting">
  <style>
    .setting input {
      background: {{bgColor}};
    }
  </style>
  <input class="setting" type="text" v-model="bgColor">
</div>

The value from the input should update the value of the css style. Whenever done with simple div elements this works, but style tags seem to be a problem

The javascript set up is the following:

new Vue({
    el: '.setting',
    data: {
      bgColor: 'red'
    }
});

However when the style tags have a specific id, this could work, but I can't bind it to an input field.

<style id="setting">
  #blue {
    background: {{bg}}
  }
  #blue:hover {
    background: {{bgHover}}
  }
</style>

<div id="blue"></div>

and the js:

new Vue({
    el: '#setting',
    data: {
      bg: 'blue',
      bgHover: 'red'
    }
});

Can someone help me understand how I can achieve updating values between style tags. jsfiddle set up

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's what I think is a good workaround/solution.

It is just a custom component, so it's as reusable as it gets. All of Vue's goods like v-if can all be used.

Another pro is that the styles generated will be there only as long as the component is!

Vue.component('v-style', {
  render: function (createElement) {
    return createElement('style', this.$slots.default)
  }
});


// demo usage, check the template
new Vue({
  el: '#app',
  data: {
    bgColor: 'red'
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app" class="stuff">
  <v-style>
    .stuff input {
      background: {{bgColor}};
    }
  </v-style>

  Remove "red" and type "yellow":
  <input class="setting" type="text" v-model="bgColor">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...