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
507 views
in Technique[技术] by (71.8m points)

css - Vue.js dynamic <style> with variables

Is it possible to add the dynamic variable in style?

I mean something like:

<style>
 .class_name{
  background-image({{project.background}});
 }
@media all and (-webkit-min-device-pixel-ratio : 1.5),
 all and (-o-min-device-pixel-ratio: 3/2),
 all and (min--moz-device-pixel-ratio: 1.5),
 all and (min-device-pixel-ratio: 1.5) {
 .class_name{
  background-image({{project.background_retina}});
 } 
}
</style>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The best way to include dynamic styles is to use CSS variables. To avoid inline styles while gaining the benefit (or necessity—e.g., user-defined colors within a data payload) of dynamic styling, use a <style> tag inside of the <template> (so that values can be inserted by Vue). Use a :root pseudo-class to contain the variables so that they are accessible across the CSS scope of the application.

Note that some CSS values, like url() cannot be interpolated, so they need to be complete variables.

Example (Nuxt .vue with ES6/ES2015 syntax):

<template>

<div>
  <style>
    :root {
      --accent-color: {{ accentColor }};
      --hero-image: url('{{ heroImage }}');
    }
  </style>
  <div class="punchy">
    <h1>Pow.</h1>
  </div>
</div>

</template>
<script>

export default {
  data() { return {
    accentColor: '#f00',
    heroImage: 'https://vuejs.org/images/logo.png',
  }},
}

</script>
<style>

.punchy {
  background-image: var(--hero-image);
  border: 4px solid var(--accent-color);
  display: inline-block;
  width: 250px; height: 250px;
}
h1 {
  color: var(--accent-color);
}

</style>

Also created an alternate more involved runnable example on Codepen.


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

...