实例_评论区功能的实时更新
练习目的:使用localstorage进行本地储存,并借此完成类评论功能的实时提交与显示功能
- html(bs4框架)
<body>
<div id="app">
<div class="container">
<div class="card">
<div class="card-header bg-dark text-center text-white">
<span>评论列表</span>
</div>
<div class="card-body form-group">
<label for="name" class="form-inline">
<span class="col-2 text-right">name:</span>
<input type="text" class="form-control col-8 border-dark" v-model="name">
</label>
<label for="content" class="form-inline">
<span class="col-2 text-right">content:</span>
<textarea name="" id="" cols="30" rows="5" class="form-control col-8 border-dark"
v-model="content"></textarea>
</label>
<input type="button" value="提交" class="btn btn-light btn-outline-dark col-4 offset-4"
@click="postContent">
</div>
<div class="card-footer">
<ul class="list-group" v-for="(item,index) in list" :key="item.id">
<li class="list-group-item col-12">
<span class="badge badge-dark">评论人:{{item.name}}</span>
{{item.content}}
</li>
</ul>
</div>
</div>
</div>
</div>
- javascript(vue框架)
<script>
var vm = new Vue({
el: "#app",
data: {
list: [{
id: 646845,
name: 'xjs',
content: 'sdcjwgcdhhe'
}, {
id: 561526,
name: 'jsu',
content: 'sabdachoj'
}],//测试用数据
name: '',
content: ''
},
methods: {
postContent() {
var newContent = {
id: '',
name: this.name,
content: this.content
};
var localStorageList = JSON.parse(localStorage.getItem('cots') || '[]');
//在loaclStorage中获取本地储存的数据,需要注意的是这些数据在第一次获取的时候可能不存在.使用空数组代替会返回空数组.
var id = (function chkId() {
var randomId = Math.floor(Math.random() * Math.pow(10, 5));
if (localStorageList.some((item, index, array) => {
if (item.id == randomId) {
return true;
}
})) {
arguments.callee();
} else {
return randomId;
}
})();//检查随机分配的id是否存在,确保所有评论的id都不同
newContent.id = id;
localStorageList.push(newContent);
localStorage.setItem('cots', JSON.stringify(localStorageList));
this.list = localStorageList;
this.name = this.content = '';
},
loadContent() {
var list = JSON.parse(localStorage.getItem('cots') || '[]');
this.list = list;
}
},
created() {
this.loadContent();//第一次进入创建实例时即获取评论数据,created是vue可以获取可以获取data数据最早的生命周期
},
filters: {},
directives: {},
components: {},
watch: {},
computed: {}
});
</script>
【推荐】FFA 2024大会视频回放:Apache Flink 的过去、现在及未来
【推荐】中国电信天翼云云端翼购节,2核2G云服务器一口价38元/年
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步