这是商店:
import { ref } from "vue";
// Store for all data
export const countriesData = ref();
export const isLoading = ref(true);
async function getData() {
try {
isLoading.value = true;
const response = await fetch("https://restcountries.com/v3.1/all");
const data = await response.json();
countriesData.value = data;
} catch (error) {
console.error("error", error);
} finally {
isLoading.value = false;
}
}
getData();
// Store for filtered data
export const filteredData = ref(countriesData);
countryData 应该使用异步 getData() 更新一次,然后就不再更改。根据应用程序中其他位置的搜索和过滤,filteredData 确实会发生变化。
这是搜索输入代码:
<script setup>
import { ref } from "vue";
import { countriesData, filteredData } from "../../store/store";
const searchValue = ref("");
function handleSubmit(e) {
e.preventDefault();
console.log(countriesData.value.length);
for (let i = 0; i < countriesData.value.length; i++) {
console.log(countriesData.value.length);
if (
countriesData.value[i].name.common.toLowerCase() ===
searchValue.value.toLowerCase().trim()
) {
filteredData.value = [countriesData.value[i]];
// setError(false);
searchValue.value = "";
return;
} else {
// setError(true);
}
}
}
</script>
无论出于何种原因,运行此 for 循环后(有效,我得到了我搜索的正确国家/地区),原始商店,countriesData,更改为仅给我countriesData.value[i]。
filteredData 应该是countriesData.value[i],我不知道为什么countryData 也更改为countriesData.value[i]。
代码
filteredData.value = [countriesData.value[i]];
在循环中似乎会导致filteredData和countriesData都更改为countriesData.value[i],所以如果我注释掉该行,原始的countriesData存储将保持不变。
如何仅更改过滤后的数据并保持国家/地区数据不变?
如果没有最小可重现示例,我们无法确定,但在声明
.value
变量时,您似乎缺少 filteredData
。你所做的基本上是说 filteredData
应该等于“ref”countriesData
。这可能就是两个变量同时更新的原因。
在任何情况下,如果您想确保两个变量都没有链接,您可以使用
spread 语法将
countriesData
深度复制到 filteredData
变量中。
export const filteredData = ref([...countriesData.value]);
这将确保
filteredData
引用仅包含 countriesData
中包含的数组的副本。
附注您似乎在
await
通话之前错过了 getData()
。
当将filteredData设置为countriesData的引用时,您指向相同的值,因此如果您编辑fileredData,您就在不知不觉中编辑了countriesData。为了避免这种情况,如果你想将countriesData存储到filteredData中,你需要生成一份countriesData的副本。
const filteredData = ref([...countriesData.value])