<template>
<table>
<tr>
<td colspan="4">全校学生统计表td>
tr>
<tr>
<td>年级td>
<td>班级数量td>
<td>班级人数td>
<td>年级人数td>
tr>
table>
<table v-for="(index) in nj" :key="index">
<tr>
<td>{{ nj[index] }}td>
<td>{{ bjCount[index] }}td>
<td>{{ bjNumber[index] }}td>
<td>{{ njNumber(index) }}td>
tr>
table>
<div>总计:{{ Count }}人div>
template>
<script setup>
import { computed } from 'vue'
const nj = [1, 2, 3, 4, 5, 6]
const bjCount = [3, 4, 3, 4, 4, 5]
const bjNumber = [30, 35, 40, 35, 40, 30]
let value
const njNumber = (index) => {
value = computed(() => {
return bjCount[index] * bjNumber[index]
})
}
const Count = () => {
let count = 0
for (let i = 0; i < nj.length; i++) {
njNumber(i)
count += value
}
return count
}
script>
<style scoped>
table {
margin: 0 auto;
}
td {
border: black solid 1px;
width: 100px;
}
style>
为啥我的预览结果是这样的,谁能 帮我看下什么问题
computed应该被用于创建计算属性,而不是在计算属性中使用
<template>
<table>
<tr>
<td colspan="4">全校学生统计表</td>
</tr>
<tr>
<td>年级</td>
<td>班级数量</td>
<td>班级人数</td>
<td>年级人数</td>
</tr>
</table>
<table v-for="(item,index,key) in nj" :key="index">
<tr>
<td>{{ nj[index] }}</td>
<td>{{ bjCount[index] }}</td>
<td>{{ bjNumber[index] }}</td>
<td>{{ njNumber(index) }}</td>
</tr>
</table>
<div>总计:{{ Count }}人</div>
</template>
<script setup>
import { computed } from 'vue'
const nj = [1, 2, 3, 4, 5, 6]
const bjCount = [3, 4, 3, 4, 4, 5]
const bjNumber = [30, 35, 40, 35, 40, 30]
const njNumber = (index) => {
return bjCount[index] * bjNumber[index]
}
const Count = computed(() => {
let count = 0
for (let i = 0; i < nj.length; i++) {
count += njNumber(i)
}
return count
})
</script>
<style scoped>
table {
margin: 0 auto;
}
td {
border: black solid 1px;
width: 100px;
}
</style>
你的代码中,Count 是一个函数,而不是一个计算属性。在模板中,你应该使用计算属性而不是函数来获得一个响应式的值。
当你在模板中使用 Count 时,Vue 会把 Count 当成一个函数,并且直接把这个函数的定义渲染到页面上。
要将 Count 转换为计算属性,你可以使用 computed 函数。在 computed 函数中,你可以返回 Count 函数的结果。例如:
<script setup>
import { computed } from 'vue'
// ...你的代码...
const Count = computed(() => {
let count = 0
for (let i = 0; i < nj.length; i++) {
njNumber(i)
count += value.value
}
return count
})
</script>