premise:
requirements are shown in the following figure:
Editing and adding items are on the same page, and the routing configuration is as follows:
routes: [{
path: "add",
component: () => import("@/views/product/edit"),
name: "product-add",
meta: { title: "" }
}, {
path: "edit/:id",
component: () => import("@/views/product/edit"),
name: "product-edit",
meta: { title: "" }
}]
solution:
my original practice is as follows:
computed:{
id:{
return this.$route.params.id
}
}
watch:{
if (val) {
this.getDetail() //
} else {
this.reset() //
}
}
this approach has a drawback:
assume that there is now a list page (list.vue) and a details page (detail.vue) that can view individual pieces of data on the list page. The route is as follows:
routes: [{
path: "list",
component: () => import("@/views/product/list"),
name: "list",
meta: { title: "" }
}, {
path: "list/:id",
component: () => import("@/views/product/detail"),
name: "detail",
meta: { title: "" }
}]
if I have opened the edit page edit.vue of a product (url is / edit/12), and then open the details page of the list detail.vue (url is / list/34), the id in edit.vue will become the id, in detail.vue, which is 34. Because this item data of id=34 does not exist, an error will be reported when calling the background interface. The solution is to change the name of the parameter in the route (that is, id), but there are too many cases of viewing the details page in the project, and it is difficult for each route that needs to view the details page to use a unique parameter name (for me, that"s the case! Because there are too many requirements in my current project that need to see the details page), I changed it to the following solution:
data:{
id: ""
},
beforeRouteEnter (to, from, next) {
next(vm => {
vm.id = to.params.id || "" // :to.params.idid;id
})
},
beforeRouteUpdate (to, from, next) {
this.id = to.params.id
next()
},
watch:{
if (val) {
this.getDetail()
} else {
this.reset()
}
}
but there is a new problem. I found that the callback function of next in beforeRouteEnter (vm = > {vm.id = to.params.id | |"}) is sometimes not executed. If I open the edit page first, it will be executed, and then the new page will be opened, it will not be executed. If I open the new page first, it will be executed, and then the edit page will be opened, it will not be executed. What is the reason for this? Please help me solve the problem. If there is a better way to implement it, please let me know, thank you