看起来你在使用 Vue 3,并尝试使用 nutui.jd 组件库中的 Category 和 CategoryPane 组件来渲染商品分类。但从你的描述中,似乎你的右侧数据(即子分类)没有正确渲染。
首先,我注意到你在 fetch 数据并更新 data
对象时使用了异步操作(Promise 和 setTimeout)。这可能会导致数据在组件渲染之前未能正确更新。此外,当你在 fetch 的 .then()
中直接输出 res
时,它可能并没有以你期望的格式返回。
另外,我注意到在 changeText
方法中,你尝试通过索引更新 categoryChild
。然而,此操作可能会导致数组引用错误,因为你没有为它创建一个新的数组。当你更改数组的任何元素而不更改整个数组的引用时,Vue 可能无法检测到这种变化。
以下是我为你提供的一些可能的解决方案:
- 使用 Vue 的
async/await
功能来处理 fetch 的异步操作,确保数据在组件渲染前正确更新。 - 检查 fetch 的响应,确保它返回了正确的数据格式。
- 在更新
categoryChild
时,创建一个新的数组。
以下是你的代码的修改版本:
<template>
<nut-category :category="category" @change="changeText">
<nut-categorypane
type="text"
:categoryChild="categoryChild"
@onChange="onChange"
/>
</nut-category>
</template>
<script>
import { reactive, onMounted } from 'vue';
export default {
setup() {
const data = reactive({
categoryInfo: {},
category: [{}],
categoryChild: []
});
onMounted(async () => {
try {
const response = await fetch('https://storage.360buyimg.com/nutui/3x/categoryData.js');
const res = await response.json();
if (res && res.categoryInfo && res.categoryInfo.category) {
data.categoryInfo = res.categoryInfo;
data.category = res.categoryInfo.category;
data.categoryChild = [...res.categoryInfo.category[0].children]; // Assuming the first level children are loaded with the parent category
}
} catch (err) {
console.log('Oh, error', err);
}
});
const changeText = (index) => {
const newCategoryChildren = [...data.categoryInfo.category[index + 1].children]; // Assuming the children are always at index + 1
data.categoryChild = [...newCategoryChildren]; // Creating a new array reference
};
const onChange = () => {
console.log("当前分类数据");
};
return {
changeText,
onChange,
...toRefs(data)
};
}
};
</script>
这个修改的代码片段使用了 async/await 来处理 fetch 的异步操作,并且确保在组件挂载后获取数据。此外,我假设你的数据结构是每个 category 对象都有一个名为 children
的属性,并且它是一个数组。如果你的数据结构不同,你可能需要根据实际情况调整这些代码。