understand

By default, the switched routing component object is released dead and recreated when it comes back

If you can cache routing component objects, you can improve the user experience

The solution

  1. Add a key attribute to the router-view
<router-view :key="$route.fullPath"/> 
Copy the code

Add a key attribute to the router-view: simple and crude, similar to v-if: will destroy the rebuild component, resulting in a performance loss

  1. Use watch to listen for ID changes and pull the interface again
export default {
  name: 'TopCategory'.components: { GoodsItem },
  setup () {
    console.log('Setup... ')
    / / round figure
    const sliders = ref([])
    // findBanner().then(data => {
    // console.log('findBanner', data)
    // sliders.value = data.result
    // })

    // Categorize data
    const route = useRoute()
    const cate = ref({})
    // findTopCategory(route.params.id).then(data => {
    // console.log('findTopCategory', data)
    // cate.value = data.result
    // })

    // Listen for changes to route.params.id
    / / watch (| | array object function, (newVal, oldVal) = > {}, {immediate: true | false, deep: true | false})
    watch(() = > route.params.id, (newVal) = > {
      console.log('route.params.id changed... ', newVal)

      findBanner().then(data= > {
        console.log('findBanner', data)
        sliders.value = data.result
      })
      findTopCategory(route.params.id).then(data= > {
        console.log('findTopCategory', data)
        cate.value = data.result
      })
    }, { immediate: true })
    return { sliders, cate }
  }
}
</script>
Copy the code

Watch (route.param.id): Not destroyed and rebuilt. Approach the resend request in a lower-level way, listening for changes in responsive data

  1. useonBeforeRouteUpdateHook function
<script>
import { onMounted, ref } from 'vue'
import { findBanner } from '@/api/home.js'
import { findTopCategory } from '@/api/category.js'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import GoodsItem from './components/goods-item.vue'

export default {
  name: 'TopCategory'.components: { GoodsItem },
  setup () {
    / / round figure
    const sliders = ref([])

    // Categorize data
    const route = useRoute()
    const cate = ref({})

    const loadData = (id) = > {
      findBanner().then(data= > {
        console.log('findBanner', data)
        sliders.value = data.result
      })
      findTopCategory(id).then(data= > {
        console.log('findTopCategory', data)
        cate.value = data.result
      })
    }

    // Execute only once
    onMounted(() = > {
      loadData(route.params.id)
    })

    // Run when the route changes
    // to: route object to jump to
    onBeforeRouteUpdate((to) = > {
      console.log('onBeforeRouteUpdate............... ', to)
      loadData(to.params.id)
    })
    return { sliders, cate }
  }
}
</script>
Copy the code

OnBeforeRouteUpdate: No destroy rebuild. Understanding is more natural