Vue生命周期如何运作?并将其用于骨架和加载 App.vue

问题描述

这个问题我的表情很傻,但是我被卡在了里面! 我使用的是Vuetify骨架,并创建了如下代码的数据isLoading。在页面刷新上,一切都很好,但是在路线更改(在我的页面中来回移动)上则无法正常工作。

在我的代码中,刷新页面btn被禁用,mycomponent在其文件中使用相同的isLoading显示框架。但是当我继续前进并返回它时,我的btn已加载而不是禁用,一段时间后未显示骨骼,而加载了mycomponent!

出什么问题了!我认为这与使用生命周期有关!

<template>
    <div>
        <v-btn :disabled="isLoading">Button</v-btn>
        <mycomponent />
    </div>
</template>

<script>
import mycomponent from '~/components/mycomponent'

export default {
    components:{
        'mycomponent': mycomponent
    },data(){
        return{
            isLoading: true
        }
    },created(){
        this.isLoading = true
    },mounted(){
        this.isLoading = false
    }
}
</script>

mycomponent:

<template>
    <v-skeleton-loader
    :loading="isLoading"
    type="button"
    width="100%"
    >
        <v-btn>Button</v-btn>
    </v-skeleton-loader>
</template>

<script>

export default {
    data(){
        return{
            isLoading: true
        }
    },mounted(){
        this.isLoading = false
    }
}
</script>

所以问题:仅当我第一次登陆页面或刷新浏览器时,它才起作用。通过前进并返回此页面disable buttonskeleton on component均无效。

更新

我正在使用NuxtJs v2.13

解决方法

创建vue实例时调用created钩子,并且在DOM中安装了vue实例时调用mounted钩子。第一次将组件路由至或刷新页面时,将调用这些挂钩。这就解释了为什么只有当您第一次进入页面或刷新浏览器时,它才起作用。

在安装组件后,在浏览器上按返回按钮将不会调用createdmounted钩子。

要解决您的问题,您可以这样做,观看$route对象

App.vue

watch: {
  '$route' () {
     // this will be called any time the route changes
     this.isLoading = true // you can think of a way to make isLoading false
   }
},

有关生命周期挂钩的更多信息,请查看此article