문제 설명
상점 값을 가져온 후 Vue 리디렉션 (Vue redirect after getting store's values)
입력 값이 vuex 저장소에서 오는 편집 페이지 /edit/:id를 만들려고 했지만 저장소에 params의 동일한 ID를 가진 작업이 없으면 /404로 리디렉션하고 싶은데 어떻게 해야 하나요? created()를 시도했지만 작동하지 않았습니다. 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>
참조 솔루션
방법 1:
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>
(by Martin Pilaszek、Lars)