<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>发表评论</title>
<script src="./lib/vue.js"></script>
<style>
ul {
list-style: none;
padding: 0 20px;
padding-top: 50px;
}
ul li {
margin: 20px 0;
}
.pinglunren {
display: inline-block;
text-align: end;
padding: 5px 20px;
border-radius: 20px;
background-color: silver;
}
</style>
</head>
<body>
<div id="app">
<!-- 子组件的发布框 -->
<!-- 4.当子组件点击发布按钮是调用组组件的刷新页面的函数 -->
<fabu @shuaxin="zhanshi"></fabu>
<!-- 发表评论的展示区域 -->
<ul>
<li v-for="item in list" :key="item.id">
<span>{{item.content}}</span> <span class="pinglunren"> 评论人:{{item.name}}</span>
</li>
</ul>
</div>
<template id="pinglun">
<div>
<label for="">评论人</label>
<input type="text" v-model="renming">
<br>
<br>
<label for="">评论内容:</label>
<input type="text" v-model="neirong">
<input type="button" value="发布评论" @click="fbinfo">
</div>
</template>
<script>
var vm = new Vue({
el: "#app",
data: {
list: [
{ id: Date.now(), name: ‘张三‘, content: ‘我张三发表的一个评论‘ },
{ id: Date.now(), name: ‘李四‘, content: ‘我李四发表的一个评论‘ },
{ id: Date.now(), name: ‘张三‘, content: ‘我张三发表的一个评论‘ }
]
},
methods: {
//3.页面已加载就现将原来的localStorage中的数据取出来,并渲染页面
zhanshi() {
var bendilist = JSON.parse(localStorage.getItem("newxin")) || [];
this.list = bendilist
}
},
created() {
this.zhanshi()
},
components: {
‘fabu‘: {
data() {
return {
renming: ‘‘,
neirong: ‘‘,
}
},
template: "#pinglun",
methods: {
fbinfo() {
console.log(this.renming)
//1.页面已加载就现将原来的localStorage中的数据取出来,由于localStorage存放的是字符串,而我们需要的数组,所以要先进行转换,当本地里面没有数据,就返回一下空数组
var bendilist = JSON.parse(localStorage.getItem("newxin")) || []
//2.将获取过来的内容存到localStorage,由于localStorage必须要存入字符串,
var newinfo = { id: Date.now(), name: this.renming, content: this.neirong }
bendilist.unshift(newinfo)
localStorage.setItem("newxin", JSON.stringify(bendilist))
//5.调用父组件的函数
this.$emit("shuaxin")
this.renming = "",
this.neirong = ""
},
},
}
}
})
</script>
</body>
</html>