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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…