先列出数据格式
[{username: "1", content: "2", dataTime: 1534128070979},{username: "11", content: "22", dataTime: 1534128070979}]
从vuex中获取到的数据,然后循环渲染。dataTime是一个时间戳,然后处理的方法是_updateTimeString。再将这个方法用定时器处理。我发现只能接收到第一次的数据item的数据,其他的为空了。一开始以为是的前后顺序的问题,各种尝试没能结解决。现在我怀疑的方向是双括号模板中可能就渲染一次了,就会造成不再往下穿参了。也考虑在{{}}中直接返回一个变量,但是因为循环中在处理就比较麻烦了,求指点迷津
<template>
<div class="comment-list" v-if="comments().length>0">
<div class='comment' v-for="(item,index) in comments()" :key="index">
<div class='comment-user'>
<span class='comment-username'>
{{item.username}}:
</span>
</div>
<p>{{item.content}}</p>
<span class='comment-createdtime'>
{{_updateTimeString(item.dataTime)}}
</span>
<span class='comment-delete' @click="handleDeleteComment(index)">
删除
</span>
</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
name: 'comment-list',
data () {
return {
timer : Object,
timeString:"123"
}
},
created(){
// this.timer = setInterval(this._updateTimeString,1000)
},
methods:{
...mapState({
comments:state=>state.comments
}),
handleDeleteComment(index){
console.log(this.comments())
let newComment = this.comments().splice(index,1);
localStorage.setItem("comments",JSON.stringify(this.comments()))
},
_updateTimeString:(item)=>{
let duration = (+new Date() - item) / 1000;
let timeString = duration > 60?`${Math.round(duration/60)}分钟前`:`${Math.round(duration)}秒前`;
return timeString;
}
},
computed:{
// _updateTimeString:(item)=>{
// let thisItem = item;
// let duration = (+new Date() - item) / 1000;
// let timeString = duration > 60?`${Math.round(duration/60)}分钟前`:`${Math.round(duration)}秒前`;
// console.log(thisItem)
// return timeString;
// }
},
mounted(){
// this.timer = setInterval(this._updateTimeString,1000)
}
}
</script>
是的, 每次循环只有一次_updateTimeString调用, 之后定时器调用这个方法并不会累加时间
数据驱动视图, 需要你说的第二种方法来实现