Problem: when several pages are rendered under the same route and the page id is changed, the page address is changed but the page does not change (view is not updated)
If the address is changed, the page is created only once, the request is not sent again, and the setup is executed only once, so the page is not refreshed
Solution 1:
Example Add the key attribute to the route egress
<RouterView :key="$router.fullPath">
Copy the code
The key is used to determine whether the virtual DOM should be destroyed and rebuilt
Formula:
Render function (data) ===> virtual DOM
Render function 1 (data) ===> virtual dom1
Render function 2 (data) ===> virtual dom2
Vue compares virtual DOM1 and virtual DOM2 (diff algorithm) to decide whether to update the page (which parts to update)
Key is used to compare virtual dom1 and virtual Dom2 when diff algorithm works.
If the keys are the same, they are not updated
If the key is different, be sure to update it
Advantages: simple and rough;
Disadvantages: Similar to v-IF destruction and reconstruction components, there will be a certain performance loss;
Solution 2:
Use watch to listen for changes in the route ID and resend the request. Add the third parameter “immediate:true” to the request
setup(){
watch(() = >route.params.id,(newVal) = >{
// Send the required request}, {immediate:true})}Copy the code
Advantages: There is no destruction rebuild, and a lower level approach (listening for responsive data changes) to access resend requests
Disadvantages: more code
Solution three:
Use the hook function onBeforeRouteUpdate (only executed when the route changes)
The request is still sent once the first time you create it
Note: there is a loophole in this hook function that sends the request with the value of its argument (to.params.id). If the request is sent with the same argument, it will send the request with the same argument as the previous one, causing the request to be corruptedCopy the code
onBeforeRouteUpdate((to) = >{
// Send the required request
})
Copy the code
The detailed code is as follows:
import { ref, onMounted } from 'vue'
import {useRoute, onBeforeRouteUpdate} from 'Vue -router setup(){const route = useRoute() const cate = ref({}) const loadCategoryList = (id) => {// Get current data FindTopCategory (id).then(data => {cate. Value = data.result})} onMounted(() => {data => {cate. Value = data.result}) LoadCategoryList (route.params.id)}) // Automatically execute before updating after route jump // beforeEach((to,from,next)=>{}) onBeforeRouteUpdate((to) =>{ LoadCategoryList (to.params.id)}) return {cate}}Copy the code
Advantages: no destruction reconstruction, logic is more intuitive disadvantage: more code