Why doesn't Nuxtjs update template when data changes?

853 Views Asked by At

I have a component in Nuxt with the following HTML in the template:

<div class="slider" id="slider" ref="slider" :style="'transform: transitionX(-' + sliderPosition + '%)'">

Then I also have a data variable:

export default {
      data() {
         return { 
            sliderPosition: 0
         }
      },
      methods: {
         moveLeft() {
            this.sliderPosition -= 25
            console.log(this.sliderPosition)
         },

Now, every time I click the button that triggers the method, the console logs out the incremented sliderPosition value. But in the template it always stays 0 and never updates - the transitionX is never changed (shows 0% in Chrome inspector and doesn't change).

Why could this be?

1

There are 1 best solutions below

1
Michal Levý On BEST ANSWER
  1. There is no transform function transitionX - docs. I guess you wanted translateX
  2. Your sliderPosition is negative and you have a - in the style expression. So if the value of sliderPosition is -25 the style is translateX(--25) which is not valid

So just to be clear, this is not a problem of Vue not updating the DOM but instead problem of browser not accepting invalid style...

const vm = new Vue({
  el: '#app',
  data() {
    return {
      sliderPosition: 0
    }
  },
  methods: {
    move(percent) {
      this.sliderPosition += percent
      console.log(this.sliderPosition)
    },
  },
  computed: {
    sliderStyle() {
      return {
        transform: `translateX(${this.sliderPosition}%)`
      }    
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<div id="app">
  <button @click="move(-5)">Move left</button>
  <button @click="move(5)">Move right</button>
  <div class="slider" id="slider" ref="slider" :style="sliderStyle">This is OK!
  </div>
  <div class="slider" id="slider" ref="slider" :style="`transform: translateX(-${this.sliderPosition}%)`">This is not!
  </div>
</div>