[List——>Details] On the same page, switching different components will cause the routing to change, but the data will not be overloaded.

On the same page, switching between different components will cause the routing to change, but the data will not be overloaded.

Problems that easily occur when nesting routes:
List->Details problems:

​ When the list and details are in the same parent component view, the details are introduced through 'sub-route'. At this time, if the routes /detail/1, /detail/2 are modified, the detail component will only be loaded once, and the routing component will not be loaded due to routing. changes while reloading.

​ This is due to the comparison of Vue's underlying virtual DOM, which caches the detail component. This will cause the life cycle function in the detail component to not be re-called, and the data will not be re-initialized. The phenomenon seen is: updating routing, data The view does not change, it will change after refreshing it

There are two solutions:
1. Another approach: provide an independent key for router-view so that the detail component is reloaded every time

<template>
  <div class="flex">
      <ul>
        <li v-for="i in 3" :key="i" @click="$router.push({
    
    
           name:'detail',
           params:{
    
    id:i}
        })">列表{
    
    {
    
     i }}</li>
      </ul>
      <div class="container">
      //key的值与路由相同,容易区分,也可以是其他随机值
        <router-view :key="$route.path"></router-view>
      </div>
  </div>
</template>

2. vue-router official recommendation: watch $router in the detail component, and write all business codes in the listener (advantages: components are not overloaded, data can be partially updated, and performance is high, disadvantages: code writing is easy to get confused)

export default {
    
    
// 详情业务
  data () {
    
    
    return {
    
    
      count: '详情页面' + this.$route.params.id
    }
  },
  created () {
    
    
    alert('create')
  },
  mounted () {
    
    
    alert('mounted')
  }
  监听路由,重载页面
  watch: {
    
    
    $route (newVal, oldVal) {
    
    
      alert(newVal.fullPath)
      this.count = '详情页面' + this.$route.params.id
      alert('create')
      alert('mounted')
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_71452134/article/details/131383501