包裹路由-组件。缓存组件,之后组件不会被销毁。组件对应的生命周期函数不会重新触发。

  1. //App.vue
  2. <keep-alive>
  3. <router-view/>
  4. </keep-alive>

使用keep-alive包裹之后会多那两个生命周期函数,activated()和 deactivated()

4-1使用activated(){}替代mounted(){}发送请求

  1. export default {
  2. name:"Detail",
  3. data(){
  4. return{
  5. imgUrl:""
  6. }
  7. },
  8. mounted(){},
  9. activated(){
  10. var id=this.$route.params.id;
  11. var url=`http://192.168.14.49:5000/playlist/detail?id=${id}`;
  12. this.axios.get(url).then(res=>{
  13. this.imgUrl=res.data.playlist.creator.avatarUrl;
  14. })
  15. console.log("发送detail-http")
  16. },

4-2还可以使用exclude

  1. //exclude:不包含哪一个.vue页面,一定要给组件name属性
  2. <script>
  3. export default {
  4. name:"Detail", //name名必须加
  5. data(){
  6. return{
  7. imgUrl:""
  8. }
  9. },
  10. mounted(){
  11. var id=this.$route.params.id;
  12. var url=`http://192.168.14.49:5000/playlist/detail?id=${id}`;
  13. this.axios.get(url).then(res=>{
  14. this.imgUrl=res.data.playlist.creator.avatarUrl;
  15. })
  16. console.log("发送detail-http")
  17. },
  18. }
  19. </script>
  20. //App.vue
  21. <keep-alive exclude="Detail">
  22. <router-view/>
  23. </keep-alive>