首页 > 解决方案 > 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>

我的组件:

<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
        }
    },
    created(){
        this.isLoading = true
    },
    mounted(){
        this.isLoading = false
    }
}
</script>

所以问题:它只在我第一次登陆页面或刷新浏览器时才有效。通过前进和返回此页面既不disable buttonskeleton on component不起作用。

更新

我在 NuxtJs v2.13

标签: vue.jsvuejs2vuetify.jsnuxt.js

解决方案


created创建 vue 实例时调用该钩子mounted,当 vue 实例已安装在 DOM 中时调用该钩子。当组件第一次被路由到或者页面被刷新时,这些钩子会被调用。这就解释了为什么它只在您第一次登陆页面或刷新浏览器时才有效。

安装组件后,按浏览器上的后退按钮不会调用createdandmounted挂钩。

要解决您的问题,您可以通过以下方式观察$route对象

应用程序.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
   }
},

有关生命周期挂钩的更多信息,请查看这篇文章


推荐阅读