I was trying to make an edit page /edit/:id where input's value comes from the vuex store, but if the store doesn't have a task with the same id of the params I want to redirect to /404, how can I achieve this? tried created() but it didn't work. Im using Vue3
<script>
export default {
name: "EditTaskForm",
data() {
return {
newTaskDesc: "",
};
},
created() {
const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
if (!task) this.$router.push("/404");
},
mounted() {
const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
this.newTaskDesc = task.desc;
},
methods: {
submitEdit() {
this.$store.dispatch("editTask", {
newTaskDesc: this.newTaskDesc,
id: Number(this.$route.params.id),
});
this.$router.push("/");
},
},
};
</script>
Try follwoing:
beforeRouteEnter(to, from, next) {
const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
if (!task) this.$router.push("/404");
},
<script>
export default {
name: "EditTaskForm",
data() { ... },
mounted() { ... },
methods: { ... },
beforeRouteEnter(to, from, next) {
const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
if (!task) this.$router.push("/404");
}
};
</script>