This code is working, but I'm new to Vue.js and I can't help but think there's a cleaner way of doing this.
In particular I mean the parts that set the data upon entrance and update (of store state) in case it's the first page you visit (or reload). I have a store that fetches data from the backend when the site loads, but that's probably obvious.
I just feel like I'm repeating myself when calling this.getTodo();
from both watch
and mounted
.
<template>
<div>
<h2>Details Page</h2>
{{ title }}
{{ content }}
{{ lastEditTime }}
</div>
</template>
<script>
export default {
data() {
return {
title: '',
content: '',
lastEditTime: ''
}
},
methods: {
getTodo () {
if (this.$store.state.list.length > 0) {
const id = this.$route.params.id;
const todoItem = this.$store.getters.getItem(id);
Object.assign(this, todoItem);
}
}
},
watch: {
'$store.state.list': {
handler() {
this.getTodo();
}
}
},
mounted () {
this.getTodo();
}
}
</script>
CodePudding user response:
Add immediate
flag to your watcher. That way its run on mounted as well every time the $store.state.list
changes.
watch: {
'$store.state.list': {
handler() {
this.getTodo();
},
immediate: true
}
}