简体   繁体   中英

How can I not combine the padding, margin styles in the Vue 3?

How can I not combine the padding, margin styles in the vue? Paddings are set dynamically .

:style="['padding-top: 3px', 'padding-right: 32px', 'padding-bottom: 3px', 'padding-left: 32px']"

generates:

<div style="padding: 3px 32px"></div>

need:

<div style="padding-top: 3px; padding-right: 32px; padding-bottom: 3px; padding-left: 32px"></div>

You've written that your code contains padding-left: 32px , which along with padding-right: 32px means the generated styling can just use shorthand padding: 0px 32px (0px top and bottom, 32px left and right) but then you say you need padding-left: 0px . What you want is in direct opposition to what you've coded. Change your code to match what you want

You need to use classes instead, and you need to make a separate class for each thing that you want to keep separate.

I do not know your motivation to do this is, but I am guessing you are creating some sort of customizable UI component where the user can change padding reactively for some reason (my best guess).

Here is how you add padding dynamically as css variables by binding the style attribute.

<template>
  <div :style="customVariables"></div>
</template>

<script setup>
//...
const pLeft = ref("32px");
const pRight = ref("20px");

const customVariables= computed(() => {
  return {
    "--p-left": pLeft.value,
    "--p-right": pRight.value,
}
//...
</script>

<style>
.p-left {
  padding-left: var(--p-left);
}

.p-right {
  padding-right: var(--p-right);
}
</style>

Vue also supports v-bind() in CSS. Docs

<script setup>
const paddings = {
  pLeft: '32px',
  pRight: '20px'
}
</script>

<template>
  <div class="p-left p-right">hello</div>
</template>

<style scoped>
.p-left {
 padding-left: v-bind("paddings.pLeft");
}

.p-right {
 padding-right: v-bind("paddings.pRight");
</style>

The values provided to CSS through v-bind will be reactive as explained in the docs:

The actual value will be compiled into a hashed CSS custom property, so the CSS is still static. The custom property will be applied to the component's root element via inline styles and reactively updated if the source value changes.


If you want to do so without using classes, then there is no way to do it, and honestly there is no real application/reason of forcing yourself to do it using "style" attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM