该页面在vue中加载了两次

时间:2019-12-18 06:50:23

标签: javascript vue.js vue-router

我在编写Vue时遇到麻烦。我正在使用vue和vuetify。

AB页。只需进入AB页面一次就没有问题。

但是,当按如下所示进入页面时,A的创建函数将被调用两次。

A-> B-> A

menuselector.vue

<template>
   <v-list>
      <template v-for='(eachmenu) in menu'>
         <v-list-item
            :to='eachmenu.path'
         >
            <v-list-item-title>
              {{eachmenu.title}}
            </v-list-item-title>
         </v-list-item>
      </template>
   </v-list>
</template>

<script>
export default {
   name: 'selector',
   data() {
      return {
         menu: [
            {
               title: 'A',
               path: '/A',
            }
            {
               title: 'B',
               path: '/B',
            }
         ]
      }
   }
}
</script>

router.vue

export default new Router({
   mode: 'history',
   base: process.env.BASE_URL,
   routes: [
      {
         path: '/',
         redirect: '/A',
         component: TestComponent,
         children: [
            {
               path: 'A',
               component: () => import('@/component/A.vue'),
               name: 'Acomponent',
            },
            {
               path: 'B',
               component: () => import('@/component/B.vue'),
               name: 'Bcomponent',
            }
         ]
      }
   ]
})

A.vue&B.vue

<template>
   test
</template>

<script>
export default {
   beforeCreate() {
      console.log('beforeCreate');
   }
   created() {
      console.log('created');
   }
}
</script>

控制台输出如下。

enter image description here

出什么问题了?

1 个答案:

答案 0 :(得分:0)

  1. 我不认为“加载”在这里是正确的词。组件所需的代码仅从服务器加载一次,因为您可以在“开发工具”的“网络”标签中检入
  2. 切换路径时,旧路径的组件被破坏,新路径的组件被创建。 Vue动态组件的默认行为(<router-view>用于切换组件)。您可以使用<keep-alive>进行更改。请务必检查文档并了解其含义-您的应用将使用更多内存
  <keep-alive>
    <router-view :key="$route.fullPath"></router-view>
  </keep-alive>