Vuejs 遍历 ref 对象
Vuejs Iterate through a ref object
我有个小问题,
我从那个方法得到我的 ref 对象
const dataAnimals = ref([])
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
})
}
getDataAnimals()
我想使用另一种方法使用该 ref 对象:
function countAnimal(type) {
dataAnimals.forEach((item) => {
if (animal.animal == type) {
total_hen += dataMint.value[animal.template_id]
}
return total_hen
})
}
const totalHen = countAnimal('hen')
但我无法遍历 :
dataAnimals.value.forEach((item) => {
有什么方法可以做到这一点吗?
谢谢:)
由于响应是一个对象而不是数组,您不能使用 forEach
对其进行迭代,您需要使用 Object.entries()
function countAnimal(type) {
let total = 0;
for (const [key, item] of Object.entries(dataAnimals)) {
if (item.animal === type) {
total++;
}
}
return total;
}
const totalHen = countAnimal('hen');
我会使用反应对象:
const dataAnimals = ref(null);
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
});
}
getDataAnimals()
当然,如果您希望该计数也具有反应性,则需要使用计算 属性.
我有个小问题, 我从那个方法得到我的 ref 对象
const dataAnimals = ref([])
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
})
}
getDataAnimals()
我想使用另一种方法使用该 ref 对象:
function countAnimal(type) {
dataAnimals.forEach((item) => {
if (animal.animal == type) {
total_hen += dataMint.value[animal.template_id]
}
return total_hen
})
}
const totalHen = countAnimal('hen')
但我无法遍历 :
dataAnimals.value.forEach((item) => {
有什么方法可以做到这一点吗?
谢谢:)
由于响应是一个对象而不是数组,您不能使用 forEach
对其进行迭代,您需要使用 Object.entries()
function countAnimal(type) {
let total = 0;
for (const [key, item] of Object.entries(dataAnimals)) {
if (item.animal === type) {
total++;
}
}
return total;
}
const totalHen = countAnimal('hen');
我会使用反应对象:
const dataAnimals = ref(null);
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
});
}
getDataAnimals()
当然,如果您希望该计数也具有反应性,则需要使用计算 属性.