Nuxt.js 中使用 keep-alive 组件的最佳实践
在 Nuxt.js 中使用 keep-alive 组件需要遵循以下步骤,以确保其正常工作:
-
配置全局 keep-alive 组件: 在
nuxt.config.js中配置build.extend,将 Vue 的 keep-alive 组件挂载到全局:<pre><code class="language-javascript">export default {build: { extend(config, { isDev, isClient }) { config.resolve.alias['vue'] = 'vue/dist/vue.common' } } }
-
在组件中使用 keep-alive: 在需要使用 keep-alive 的组件中,添加
keep-alive标签,并使用一个唯一的key值:<pre><code class="language-html"><template> -
在 Layout 中使用 keep-alive: 如果使用了 Nuxt.js 的 Layout 功能,在 layout 中也需要添加 keep-alive:
<pre><code class="language-html"><template>
如果以上步骤都已经配置好了,但 keep-alive 仍然不生效,可以尝试以下解决方案:
- 清除浏览器缓存
- 在组件中添加
activated和deactivated钩子函数,手动触发缓存:
export default {
activated() {
this.$nextTick(() => {
this.$refs.scroll.refresh() // 重新刷新缓存
})
},
deactivated() {
// do something
}
}
原文地址: https://www.cveoy.top/t/topic/mjAU 著作权归作者所有。请勿转载和采集!