我正在尝试将我的vue应用程序转换为nuxt应用程序。在我的vue应用程序中,我轻松地使用了vue-slick-corousel。但是对于nuxt来说,同样的代码经过必要的修改后,corousel就不能进行刷新了。如果我实时编辑模板,或者在不刷新页面的情况下浏览应用程序,那么在第二次访问页面时,它就能完美地工作。以下是我如何在我的nuxt应用程序中使用vue-slick-corousel
//nuxt.config.js
plugins: [
{ src: './plugins/vue-slick-carousel.js' }
],插件js文件中的代码:
//vue-slick-carousel.js
import Vue from 'vue'
import VueSlickCarousel from 'vue-slick-carousel'
Vue.component('VueSlickCarousel', VueSlickCarousel)最后,在模板中:
<!-- CustomComponent.vue -->
<template>
<div>
<VueSlickCarousel :arrows="true" :dots="true">
<div v-for="(cat, index) in categories"
:key="index"
style="height: 20px; width: 10px; background-color: red; color: white"
>
{{cat.name}}
</div>
</VueSlickCarousel>
</div>
</template>
<script>
import VueSlickCarousel from 'vue-slick-carousel'
import 'vue-slick-carousel/dist/vue-slick-carousel.css'
// optional style for arrows & dots
import 'vue-slick-carousel/dist/vue-slick-carousel-theme.css'
export default {
name: 'CustomComponent',
data() {
return {
categories: []
}
},
async fetch() {
this.categories = await fetch(
'https://*****************************/categories?limit=20'
).then(res => res.json())
},
components: {
VueSlickCarousel
},
}
</script>这是我在刷新"TypeError:无法读取未定义的属性‘长度’“时遇到的错误。
每当我从客户端重新呈现页面时,错误就会消失。已经试着把容器封住了
<client-only>尝试使用一种条件
v-if="slik.length" 没起作用。我怎样才能解决这个问题?
发布于 2021-06-06 18:16:26
编辑:这是对$fetchState.pending助手用法的解释。
fetch()是一个非阻塞钩子,它允许您在加载的页面/组件时获取数据。asyncData()是阻塞的,但只有在导航而不是在初始呈现时才会阻塞,这可能很烦人fetch()和a middleware组合进行阻塞导航。VueSlickCarousel实际上是在等待您为它提供一个项目数组。但是,在初始呈现和在获取任何数据之前,您只在categories: []中设置了data()。$fetchState.pending是一个手巧帮手,它可以告诉我们什么时候完成fetch()中的全部调用。因此,如果要调用4个不同的API,那么只有在完成所有4个调用时,它才等于false。this.$fetchState.pending = true手动设置它,但是这是强制的,应该在正确理解时使用。<VueSlickCarousel v-if="!$fetchState.pending">,我们基本上是说,在挂载这个组件之前,先把我所有的东西放到fetch()中去完成。这防止了任何.length方法的问题,因为组件本身只有在应用.length之前才会被挂载。下面是Nuxt生命周期的一个小映像,集中在fetch()钩子上。

您不应该将async/await和then混为一谈。试着只使用其中一种(我推荐第一种)。
async fetch() {
const response = await fetch(
'https://*****************************/categories?limit=20'
)
const fetchedCategories = await response.json()
console.log('categories', fetchedCategories)
this.categories = fetchedCategories
},而且,:key="index"是一个糟糕的实践,因为index在v-for中是可变的。尝试使用API中的UUID。
我很肯定这些也不是必需的:
import VueSlickCarousel from 'vue-slick-carousel'components: { VueSlickCarousel },https://stackoverflow.com/questions/67852731
复制相似问题