I've been going through a Vue.js tutorial on YouTube: Vue.js Tutorial: Beginner to Front-End Developer https://www.youtube.com/watch?v=1GNsWa_EZdw&t=48s
Most of the tutorial has been working fine for me, except for the issue with updating the navigation list. The instructor mentions using an Eventlistener for page updates around 04:01:20.
I'm facing trouble with assigning a new array to 'this.pages' to update the v-for loop in my code. What could be the reason this is not working and how can I troubleshoot it?
this.$bus.$on('page-updated', () => {
this.pages = [...this.$pages.getAllPages()];
});
Here are some relevant parts of the script:
Navbar.vue
<template>
...
<navbar-link
v-for="(page, index) in publishedPages"
class="nav-item"
:key="index"
:page="page"
:index="index"
></navbar-link>
...
</template>
<script>
import NavbarLink from './NavbarLink.vue';
export default {
components: {
NavbarLink
},
inject: ['$pages', '$bus'],
created() {
this.pages = this.$pages.getAllPages();
this.$bus.$on('page-updated', () => {
this.pages = [...this.$pages.getAllPages()];
});
},
data() {
return {
theme: 'dark',
data: []
}
},
computed: {
publishedPages() {
return this.pages.filter(p => p.published)
}
},
..
}
}
</script>
PadeEdit.vue
<script setup>
import { useRouter } from 'vue-router';
import { inject } from 'vue';
const router = useRouter();
const pages = inject('$pages');
const bus = inject('$bus');
const {index} = defineProps(['index']);
let page = pages.getSinglePage(index);
function submit() {
pages.editPage(index, page);
bus.$emit('page-updated', {
index,
page
});
...
}
...
</script>
Events.js
const events = new Map();
export default {
$on(eventName, fn) {
if (!events.has(eventName)) {
events.set(eventName, [])
}
events.get(eventName).push(fn);
},
$emit(eventName, data) {
if (events.has(eventName)) {
events.get(eventName).forEach(fn => fn(data));
}
}
};
data.js
const pagesKey = 'pages';
let pagesJson = localStorage.getItem(pagesKey);
let pagesStore = JSON.parse(pagesJson);
function save() {
localStorage.setItem(pagesKey, JSON.stringify(pagesStore));
}
export default {
addPage(page){
pagesStore.push(page);
save();
},
getAllPages() {
return pagesStore;
},
getSinglePage(index) {
return pagesStore[index];
},
editPage(index, page) {
pagesStore[index] = page;
save();
}
}