Search code examples
javascriptvue.jsvuexvuetify.js

Vuetify Slider set value from vuex store


I am trying to set an existing value from my vuex store to my vuetify slider. But it always positions to 0.

This is my slider / my code:

   <v-slider
     v-model="sizeOfFont"
     :max="40"
     :value="pureFontSize || ''"
     @change="changeFontSize()"
     append-icon="mdi-format-size"
   ></v-slider>

export default Vue.extend({
  data: () => ({
    sizeOfFont: '',
  }),

  computed:  {
    ...mapState(['font', 'fontSize']),

    pureFontSize() {
      return this.fontSize.toString().replace('px', '');
    }
  },
  methods: {
    changeFontSize() {
      this.$store.commit('setFontSize', `${this.sizeOfFont}px`);
    },
 }

If I console.log this.fontSize it actually returns the saved fontsize from my vuex store but I am unable to set it as a default value to my slider.


Solution

  • The issue is that you are using both v-model, value and change event to control the font property, and they are interacting with each other. You should use either v-model or a combination of value and change event to control the property, something like the following with v-model only:

    <v-slider
      v-model="sizeOfFont"
      :max="40"
      append-icon="mdi-format-size"
    ></v-slider>
    
    export default Vue.extend({
      computed:  {
        ...mapState(['font', 'fontSize']),
        
        sizeOfFont: {
          get() {
            return this.fontSize.toString().replace('px', '');
          },
          set(val) {
            this.$store.commit('setFontSize', `${val}px`);
          }
        }
      }
    }) 
    

    And then in your Vuex store, you can give sizeOfFont a default value, which should be picked up by v-model.