Littlemyx
Littlemyx

Reputation: 75

Vue.js recalculate computed properties on client after server rendering

I've got this simple vue single file component

<template>
  <v-layout>
    <v-flex xs12 sm6 offset-sm3>
        <v-card v-bind:color="color" class="white--text">
          <v-card-title primary-title>
            <div>
              <h3 class="headline mb-0">Kangaroo Valley Safari</h3>
              <div>{{card_text}}</div>
            </div>
          </v-card-title>
        </v-card>
    </v-flex>
  </v-layout>
</template>

<script>
import MessageCard from '../components/MessageCard.vue';
const colors = [
  'red',
  'pink',
  'purple',
  'indigo',
  'green'
];

export default {
  data () {
    return {
      card_text: 'Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui.'
    }
  },
  computed: {
    color: function () {
      const length = colors.length;
      return colors[Math.round(-0.5 + Math.random() * (length + 1))] + ' darken-3';
    }
  },
  components: {
    MessageCard
  }
}
</script>

The problem is that by server-side render I am getting computed color of v-card as a style, but when the client side hydration starts computed property recalculates which changes the style and causes rerender.

Of cause, I can fix it fix tag, but I'm curious is there some other ways to make it work correctly.

Upvotes: 1

Views: 1463

Answers (1)

Moritz
Moritz

Reputation: 471

Computed properties are always reevaluated during client side hydration. It is generally not a good idea to relay on side effects in your computeds (like Math.random()), since Vue.js expects computed properties to be idempotent. So usually you would calculate that random value once at creation and store it as data. However the data of a component is also not preserved between SSR and hydration.

So a way you could solve this, would be by storing the random value in the state of a Vuex store. It is then possible to restore the state of the store form the server in the client.

Upvotes: 2

Related Questions