使用成绩需求来实现
详细的代码示例(主要练习 Vue 简单的计算属性)
需求功能技术点
渲染功能: 不及格高亮、使用v-if v-else结局盒子互斥,使用v-bind:class解决高亮。 删除功能:点击传递id ,通过filter过滤器过滤然后覆盖原数组,使用指令修饰符。prevent阻止默认行为。 添加功能:v-model双向绑定,使用指令修饰符 (trim, number)修饰功能。在使用unshift修改数组,v-for会根据数组自动更新视图。 统计总分,求平均分:使用reduce求和(需要在computed配置项中使用计算属性函数),将计算逻辑返回的结果通过return暴露出来,然后使用差值表达式 通过 属性的方式进行渲染即可。切记计算属性和函数方法长的一样都是函数,但是,使用计算属性必须写属性。{{ 计算属性名 }},后面不要小括号。
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta http-equiv = " X-UA-Compatible" content = " IE=edge" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < link rel = " stylesheet" href = " ./styles/index.css" /> < title> Document</ title> </ head> < body> < div id = " app" class = " score-case" > < div class = " table" > < table> < thead> < tr> < th> 编号</ th> < th> 科目</ th> < th> 成绩</ th> < th> 操作</ th> </ tr> </ thead> < tbody v-if = " list.length > 0" > < tr v-for = " (item,index) in list" :key = " item.id" > < td> {{ index + 1 }}</ td> < td> {{ item.subject }}</ td> < td :class = " {red: item.score < 60}" > {{ item.score}}</ td> < td> < a @click.prevent = " del(item.id)" href = " #" > 删除</ a> </ td> </ tr> </ tbody> < tbody v-else > < tr> < td colspan = " 5" > < span class = " none" > 暂无数据</ span> </ td> </ tr> </ tbody> < tfoot> < tr> < td colspan = " 5" > < span> 总分:{{ totalCount }}</ span> < span style = " margin-left : 50px" > 平均分:{{ averageCount }}</ span> </ td> </ tr> </ tfoot> </ table> </ div> < div class = " form" > < div class = " form-item" > < div class = " label" > 科目:</ div> < div class = " input" > < input v-model.trim = " subject" type = " text" placeholder = " 请输入科目" /> </ div> </ div> < div class = " form-item" > < div class = " label" > 分数:</ div> < div class = " input" > < input v-model.number = " score" type = " text" placeholder = " 请输入分数" /> </ div> </ div> < div class = " form-item" > < div class = " label" > </ div> < div class = " input" > < button @click = " add" class = " submit" > 添加</ button> </ div> </ div> </ div> </ div> < script src = " https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js" > </ script> < script> const app = new Vue ( { el : '#app' , data : { list : [ { id : 1 , subject : '语文' , score : 20 } , { id : 7 , subject : '数学' , score : 80 } , { id : 12 , subject : '英语' , score : 70 } , ] , subject : '' , score : '' } , methods : { del ( id ) { this . list = this . list. filter ( item => item. id !== id) } , add ( ) { this . list. unshift ( { id : + new Date ( ) , subject : this . subject, score : this . score} ) } } , computed : { totalCount ( ) { return this . list. reduce ( ( sum, item ) => sum + item. score , 0 ) } , averageCount ( ) { if ( this . list. length === 0 ) { return 0 } return ( this . totalCount / this . list. length) . toFixed ( 2 ) } } } ) </ script> </ body>
</ html>