Layout doesn't update even if variable gets updated
-
Hello everybody,
i have following problem. I think it’s really simple to solve. But I can’t see my mistake.
I have the following files:
Store.js
export let store = { state: { isHouseholdSelected: false }, setSelectedHousehold: function () { this.state.isHouseholdSelected = true; }
First.vue
export default { data() { return { isHouseholdSelected: store.state.isHouseholdSelected } } }
Second.vue
export default { methods: { selectHousehold: function () { store.setSelectedHousehold(); } } }
Inside of Second.vue I trigger the method
selectHousehold()
and the value ofisHouseholdSelected
get changed. My understanding of vue is that it detects the change of the property inside of First.vue and rerenders the vue.Is the problem that Second.vue is within First.vue through a router-view component?
Thanks in advance
-
In first, you should be using a computed property if you want it to be reactive. You are currently initialising a new object with the value stored in state.
-
Thank you for your help but i don’t understand your solution completely. Originally I had the store as a class:
Store:class Store { constructor() { this.state = { isHouseholdSelected: false //... } } //... } export const store = new Store();
I created it like this as a singleton.
And why do I need a computed property? Do you mean that I should define the called function from the store as a computed property?
-
Hi. If I understand properly, your problem is that in
first.vue
,isHouseholdSelected
does not update when state changes?In that case, replace first.vue with this:
export default { computed: { isHouseholdSelected() { return this.$store.state.isHouseholdSelected } } }
Explaination
What you are currently doing in
first.vue
in initializing a new object with aisHouseholdSelected
property that is equal tostore.state.isHouseholdSelected
during initialization. The property will not update, is is static.Are you using vuex? This looks a lot like vuex. If you are, cou can use the following helper in
first.vue
```js import { mapState } from 'vuex' export default { computed: { ...mapState(['isHouseholdSelected']) } }
the
...
is called a spread operator, basically turns...[1, 2]
into1, 2
-
Thank you for your help. Until now I didn’t used vuex. I thought it is too much boilerplate. It is much easier than building a self build vuex like store.
I only needed to add around 50 lines of code to use vuex. Now everything works just fine and I can continue finishing my project.I appreciate your help. Thank you