Home > Blockchain >  vue computed properity not updating value
vue computed properity not updating value

Time:04-13

I'm trying to updated a Computed Property. The data is coming from vuex state.

I get my data from the store. I want to updated the value allowed in the store. However when I click my update button it dosn't update the value.

html

  <div @click="update">update</div>
  <b-row>
    <b-col v-for="cat in categories" :key="cat.id" sm="12" md="6" lg="4">
        <div>{{cat.allowed}}</div>
    </b-col>
  </b-row>
  computed: {
...mapGetters("categories", ["customerCategories"]),

 categories() {
   return this.customerCategories;
 },
 methods: {
    update() {
      this.categories.filter((element) => (element.allowed = true));
      console.log(this.categories); // not updating the allowed
},
 }

},

// from the store
    categories = [
  {
    allowed: false
    description: "hsdkj fskdjf skfj"
    id: 15
  },
  {
    allowed: false
    description: "blah blah"
    id: 13
  },
   {
    allowed: false
    description: "more blah blah"
    id: 13
  },
  {
    allowed: false
    description: "lots more blah blah"
    id: 1
  }
]

Even if I target the code the vuex, I'm still not updating the value

 const data = [...this.categories]
  const l =[]
  const updated = Array.from(data)
  updated.forEach(res => {
    res.allowed = 'boo'
    l.push(res)
  })
  console.log(l)

CodePudding user response:

you better update your state inside vuex and bring updated value from vuex using computed value. Because, Computed is not reactive which you cannot change it easily. If you want to change it here, you should make get and set as well. Better option, make action which mutates your state, and sort it in getters.

CodePudding user response:

The store state should not be modified outside of the store. Instead, you should use a Vuex mutation to update the store.

Declare the mutation that performs the update to state.categories:

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    categories: {
      namespaced: true,
      ⋮
      mutations: {
        SET_ALLOWED(state, value) {
          state.categories.forEach(c => c.allowed = value)
        },
      },
    },
  },
})

In your component, call commit() to use the mutation:

// MyComponent.vue
export default {
  ⋮
  methods: {
    update() {
      this.$store.commit('categories/SET_ALLOWED', true)
    },
  },
}

demo

  • Related