[Vuejs]-Not understanding Vuex

0👍

The Vuex store is reset to its initial state when you refresh the page, similar to how a normal page is reset to its initial state when you refresh it. To persist (part of) the Vuex store, you need to use a plugin for that. You could use, for example, vuex-persistedstate.

While this might help if you refresh, it would obviously not do anything if you would for example click on a link to a piece in a different project.

The other thing that when you refresh, and you have a route in the url bar that points to the route of PieceShow, Vue router will not visit ProjectShow at all.


You should always build your views with the knowledge that someone might not have visited any other route. That said, there are several ways you can get around simply duplicating your code to retrieve a project.

You can move the code for retrieving your project to a Vuex action. If the project is already loaded, just return early, otherwise retrieve the project. Guard against non-existence by using a v-if on your component so it does not render before the project has been loaded. You can even show a loader based on a variable you put in the vuex store in that case.

An other way is to nest your routes in a way that you have a route for /projects/:projectId and one for the subroute pieces/:pieceId. In the view for /projects/:projectId you can then do something like below. In your router.js you can then define an attribute children with a subroute that will be mounted in the router-view for /projects/:projectId.

<template>
  <router-view v-if="currentProject" />
</template>

<script>
export default {
  computed: {
    currentProject() {
      return this.$store.state.currentProject
    }
  },

  created () {
    const response = await PiecesService.getPieceById({
      id: this.$route.params.piece_id
    })
    const project = response.data

    this.$store.commit("setCurrentProject", project);
  }
}
</script>

Leave a comment