Categories
Vue Answers

How to use style tags inside Vue.js template and update from data model?

Spread the love

Sometimes, we want to use style tags inside Vue.js template and update from data model.

In this article, we’ll look at how to use style tags inside Vue.js template and update from data model.

How to use style tags inside Vue.js template and update from data model?

To use style tags inside Vue.js template and update from data model, we can create our own component.

For instance, we write

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

    <input class="setting" type="text" v-model="bgColor" />
  </div>
</template>

<script>
Vue.component("v-style", {
  render(createElement) {
    return createElement("style", this.$slots.default);
  },
});

//...
export default {
  //...
};
</script>

to create the v-style component with Vue.component.

We call it with an object that has the render method that calls createElement to create a 'style' element with the default slot as its content.

Then we can use it by writing

<v-style> .stuff input { background: {{ bgColor }}; } </v-style>

Conclusion

To use style tags inside Vue.js template and update from data model, we can create our own component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *