<...">

In vue.js component, how to use props in css?

I am new to vue.js. Here is my problem:

In a * .vue file, for example:

<template> <div id="a"> </div> </template> <script> export default { name: 'SquareButton', props: ['color'] } </script> <style scoped> #a { background-color: ? } <style> 

How to use color details in background-color: (where is it now ? ).

Thanks.

+22
source share
4 answers

No. You use a computed property, and there you use the option to return the div style, for example:

 <template> <div id="a" :style="style" @mouseover="mouseOver()"> </div> </template> <script> export default { name: 'SquareButton', props: ['color'], computed: { style () { return 'background-color: ' + this.hovering ? this.color: 'red'; } }, data () { return { hovering: false } }, methods: { mouseOver () { this.hovering = !this.hovering } } } </script> <style scoped> <style> 
+28
source

You really can!

You need to define CSS variables in the Computed Property, then call the computed property as a style attribute for the element that needs the CSS variable, and finally, you can use the variable in the tags at the bottom of your document.

Take a look here: https://codepen.io/richardtallent/pen/yvpERW/

 some code to make the link work. 

and here: https://github.com/vuejs/vue/issues/7346

+13
source

If you need CSS that cannot be applied by a style attribute such as pseudo-classes or media queries, I do the following:

Create a globally accessible style component when initializing Vue (you need it, otherwise you will encounter problems with linting). It creates a style tag that simply displays the contents in the slot:

I would use this only if you really need dynamic values ​​in CSS and CSS functions that cannot be applied to a style attribute.

 import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false Vue.component('v-style', { render: function(createElement) { return createElement('style', this.$slots.default) } }) new Vue({ router, store, render: h => h(App) }).$mount('#app') 

Then use it at the top of your template as follows, and you get the full JavaScript scope of your component and the full css syntax:

 <template> <v-style> @media screen and (max-width: 820px) { .gwi-text-media-{{ this.id }} { background-image: url({{ mobileThumb }}); } } </v-style> </template> 

It seems a bit hacky to me, but it works, and in some cases I would prefer to go this way, instead of adding additional JS for mouse hover or resizing, which have great potential to reduce the performance of your application.

+6
source

Why not just use :style support like this:

 <template> <div :style="{backgroundColor: color}"> </template> 

Make sure you define camelCase style CSS properties.

0
source

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


All Articles