vue 计算百分比
时间: 2023-06-29 13:12:44 浏览: 148
计算百分比可以使用 Vue 中的计算属性和过滤器。
1. 计算属性:
假设有一个数据项 `score`,表示得分,另一个数据项 `total`,表示总分,则可以通过计算属性计算出百分比:
```html
<template>
<div>
得分:{{ score }},总分:{{ total }}
<br>
百分比:{{ percentage }}
</div>
</template>
<script>
export default {
data() {
return {
score: 80,
total: 100
}
},
computed: {
percentage() {
return (this.score / this.total * 100).toFixed(2) + '%'
}
}
}
</script>
```
2. 过滤器:
也可以使用过滤器来计算百分比:
```html
<template>
<div>
得分:{{ score }},总分:{{ total }}
<br>
百分比:{{ score | percentage(total) }}
</div>
</template>
<script>
export default {
data() {
return {
score: 80,
total: 100
}
},
filters: {
percentage(total) {
return function(score) {
return (score / total * 100).toFixed(2) + '%'
}
}
}
}
</script>
```
在模板中使用 `score | percentage(total)` 表示将 `score` 作为参数传入 `percentage` 过滤器中计算百分比。