javascriptvuejs3stylespadding

Dynamically change padding in Vue js 3


Hello I want to change padding based on my selected locale, since div width is changing.

  <div
    class="input-group modal-check-show show-modal"
    :style="paddingLeft"
  >
  . . .
  </div>

const EnPaddingLeft = ref('padding-left: 27%;')
const DePaddingLeft = ref('padding-left: 28%;')
const SrPaddingLeft = ref('padding-right: 33% !important;')

const setPaddingLeft = computed(() => {
  let padding
  if (Tr.currentLocale === 'en') {
    padding = EnPaddingLeft
  } else if (Tr.currentLocale === 'de') {
    padding = DePaddingLeft
  } else if (Tr.currentLocale === 'sr') {
    padding = SrPaddingLeft
  } else {
    padding = EnPaddingLeft
  }
  return padding
})
const paddingLeft = setPaddingLeft

missing padding style

When I change computed to method it shows up at div tag, but it doesn't change padding when I change locale.


Solution

  • The primary issue in the provided code is that the computed property setPaddingLeft should be used as a reactive reference in Vue 3. Instead of directly assigning setPaddingLeft to paddingLeft.

    In your code, just remove setPaddingLeft and directly return the reactive reference paddingLeft should be fine.

    const paddingLeft = computed(() => {
      let padding
      if (Tr.currentLocale === 'en') {
        padding = EnPaddingLeft
      } else if (Tr.currentLocale === 'de') {
        padding = DePaddingLeft
      } else if (Tr.currentLocale === 'sr') {
        padding = SrPaddingLeft
      } else {
        padding = EnPaddingLeft
      }
      return padding
    })
    
    // Below assignment is not needed, and will cause issue since paddingLeft is not reactive.
    // const paddingLeft = setPaddingLeft