I have app using VueJS + Vuetify + Spring. I’m getting a travel list from server and I want to display the list of names in a navigation drawer.
I created a travelList
array and I want to fetch this list of travels before drawerElements
passes it to the navigation drawer as a prop.
Is it possible? My current code doesn’t work – probably I did something wrong, maybe there is another, better and correct way.
<template> <v-app> <app-bar/> <navigation-drawer :links="drawerElements"/> <v-main> <router-view></router-view> </v-main> </v-app> </template> <script> import AppBar from "@/views/components/AppBar"; import NavigationDrawer from "@/views/components/NavigationDrawer"; import TravelService from "@/services/travel.service"; export default { name: "Home", components: {AppBar, NavigationDrawer}, data() { return { travelList: [], drawerElements: [ { to: '/menu/home', icon: 'mdi-view-dashboard', text: 'Home', }, { icon: 'mdi-book-multiple', text: 'Travels', subLinks: this.travelList, } ] } }, computed: { currentUser() { return this.$store.state.auth.user; } }, mounted() { if (!this.currentUser) { this.$router.push('/login'); } this.getTravelList(); }, methods: { getTravelList() { TravelService.getLoggedUserTravels().then( response => { this.convertTravelToDrawerElements(response.data); } ) }, convertTravelToDrawerElements(response) { let travels = []; response.forEach(element => { let travel = {}; travel.text = element.name; travel.to = '/trip/' + element.id; travel.icon = "mdi-menu-right"; travels.push(travel); }) this.travelList = travels; } }, } </script> <style> </style>
Advertisement
Answer
You have two options
- Inside your
convertTravelToDrawerElements
method,push
every createdtravel
directly intothis.travelList
instead of replacing it with a new array - Convert
drawerElements
fromdata
into computed property
computed: { getDrawerElements() { return [ { to: '/menu/home', icon: 'mdi-view-dashboard', text: 'Home', }, { icon: 'mdi-book-multiple', text: 'Travels', subLinks: this.travelList, } ] } }
<template> <v-app> <app-bar/> <navigation-drawer :links="getDrawerElements"/> <v-main> <router-view></router-view> </v-main> </v-app> </template>
The reason
…your code doesn’t work as expected is because data()
function is called only once when your component is created. At that time, the this.travelList
is empty array. This empty array (or better say reference to the array) is assigned into subLinks
property of the new object the data()
function creates and returns. When you later replace the this.travelList
with a new array, the operation has no effect on the content of subLinks
property, it still contains the reference to the previous (and completely empty) array….