Search code examples
vue.jsvuex

Value of vuex getter not updating when switching between routed components


I have a vuex getter that takes the value of an array from my state.

import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tableRow: [
            {
                "name": 1,
                "numSongs": 2,
                "Year": 3
            }
        ]
    },
    getters:{
        tRow : state => {
            return state.tableRow
        }
    }
});

I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.

       $("#table1 tr").click(function () {
            var list = [];

            var $row = $(this).closest("tr"),
                $tds = $row.find("td");

            list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
            // self.$store.state.tableRow = list;
            this.tabRow = list;
            console.log(this.tabRow);
             self.passData();
        });
    });
},

computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }
},

Then in another one of my routed components i set the same computed property and then try to call it in the template but the value it outputs is the default values i gave it.

mounted: function () {
    var self = this;
    console.log(this.tabRow)
    // self.passedRow = self.$store.state.tableRow;
    self.passedRow = this.tabRow;
    this.startDoughnut(this.$refs.canvas, 'Doughnut');
},
    computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }

I am not properly efficient with vuex yet so i am not sure why this won't work any help would be appreciated.


Solution

  • What you are trying to do here is not possible in vue compute property and also in Vuex. Computed properties and vuex getters areread only.

     this.tabRow = list;
    ======================
     computed: {
        tabRow(){
         return this.$store.getters.tRow;
        }
    

    Do this

    computed: {
      tabRow(){
        get: function () {
          return this.$store.getters.tRow;
        },
        set: function (newValue) {
          commit('SET_TABLEROW', newValue)
        });
        }
       }
    

    In store add a mutation

     mutations:{
            SET_TABLEROW: (state,list) => {
                state.tableRow=list
            }
        }
    

    refer https://vuex.vuejs.org/en/mutations.html