<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><scriptsrc="./vue.js"></script></head><body><divid="app"><h3>新闻</h3><ul><liv-for="item in news":key="item.id"><p>城市:{{item.city}}</p><p>新闻:{{item.news}}</p><p>日期:{{item.time | filterTime}}</p></li></ul></div><script>//定义全局过滤器
Vue.filter("filterTime",(time)=>{//转换某种时间格式 == 创建时间对象,获取对应的年月日,拼接let oDate =newDate(time*1);//new Date("2023-10-7") new Date(2023,10,7),new Date(时间戳)let y = oDate.getFullYear();let m =(oDate.getMonth()+1+"").padStart(2,'0');let d =(oDate.getDate()+"").padStart(2,'0');let h =(oDate.getHours()+"").padStart(2,'0');let mi =(oDate.getMinutes()+"").padStart(2,'0');let s =(oDate.getSeconds()+"").padStart(2,'0');return`${y}-${m}-${d}${h}:${mi}:${s}`})newVue({el:"#app",data:{news:[{id:1,city:"杭州",news:"杭州亚运会",time:"1696657349946"},{id:2,city:"北京",news:"北京哈哈哈",time:"1696659454316"},{id:3,city:"上海",news:"上海呵呵呵",time:"1697657349946"}]},methods:{},})</script></body></html>
三、computed(计算属性)
3、1 computed基础使用
作用:经过计算得到的属性
语法
new Vue({
computed:{
属性名(){
//计算逻辑return 结果
}
}
})
案例
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><scriptsrc="./vue.js"></script></head><body><divid="app"><tablewidth="500"border="1"><thead><tr><th>编号</th><th>姓名</th><th>成绩</th></tr></thead><tbody><trv-for="item in students":key="item.id"><td>{{item.id}}</td><td>{{item.name}}</td><td><inputtype="text"v-model.number="item.score"></td></tr><tr><td>平均成绩</td><tdcolspan="2">{{avagScore}}</td></tr></tbody></table><h4>平均成绩方法:{{getAvag()}}</h4><h4>平均成绩方法:{{getAvag()}}</h4><h4>平均成绩方法:{{getAvag()}}</h4><h4>平均成绩方法:{{getAvag()}}</h4><h4>方法-调用一次计算一次</h4><h4>平均成绩计算属性:{{avagScore}}</h4><h4>平均成绩计算属性:{{avagScore}}</h4><h4>平均成绩计算属性:{{avagScore}}</h4><h4>平均成绩计算属性:{{avagScore}}</h4><h4>计算属性-有缓存,数据发生了变化才会重新调用计算</h4></div><script>newVue({el:"#app",data:{students:[{id:1,name:"刘备",score:99},{id:2,name:"诸葛亮",score:100},{id:3,name:"孙策",score:50},{id:4,name:"司马懿",score:85},{id:5,name:"小乔",score:70}],},methods:{getAvag(){
console.log("通过方法计算");//计算平均值let sum =0;this.students.forEach(value=>{
sum += value.score;});//返回平均成绩return(sum /this.students.length).toFixed(2)}},//mounted(){} 页面一渲染完成就需要去计算成绩//计算属性:需要计算后得到的值,就会使用计算属性//依赖数据:如果数据发生变化会重新计算computed:{//属性名(){ 计算 return 计算结果 }avagScore(){
console.log("计算属性");//计算平均值let sum =0;this.students.forEach(value=>{
sum += value.score;});//返回平均成绩return(sum /this.students.length).toFixed(2)}}})</script></body></html>