Sorry for the somewhat clumsy wording of the question. I'm a bit uncertain how to phrase it perfectly so feel free to suggest an alteration.
I have a menu system where clicking on a link loads data to the store (it dispatches a command for it to the store and tells it what kind of data that should be loaded to the state variables).
menuClick: function(event) {
const dataKind = event.target.id;
this.$store.dispatch("updateData", { type: dataKind });
}
I also have a router like this.
import Thing1 from "./thing1.vue";
export const routes = [
...,
{ path: "/stuff/thing1", component: Thing1 }
];
This setup works and I'm happy with it. Or, rather, I was happy with it until a colleague pointed out that simply typing in the URL (adding a bookmark, following a link etc., anything but the actual click on the menu item) doesn't do the trick. The page is rendered as supposed to but the data isn't loaded and so we only show the message that no bananas... there.
How can I resolve it?
One approach I'm considering is hooking up the dispatch of update request to the routing event and not only on clicking in the menu. The problem is that I don't know how to technically speaking. Is it possible at all?
The second approach would be loading the data not at a click in the menu (or at least not only at the click) but at a later stage. The problem with this approach is that I have no idea where to place the update. What would be a good spot?
Are there other approaches to consider?
You can use beforeMount or any other Lifecycle Hooks, if you have to initialise some required data. You can have a method which updates the data in the store and call that same method while initialising and on menuClick.
The structure should look like following:
export default {
components: { },
data () {
return {
}
},
methods: {
updateStore (value) {
this.$store.dispatch("updateData", { type: value })
},
menuClick: function(event) {
const dataKind = event.target.id
this.updateStore( dataKind )
}
},
beforeMount () {
if(this.$route.dataKind && someOtherConditionIfNeeded){
this.getDetails(this.$route.dataKind)
}
}
}
</script>