vue 评论列表案例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>评论列表</title>
	<link rel="stylesheet" type="text/css" href="lib/bootstrap-3.3.7.css">
</head>
<body>
	<div id="app">
		<content-box @fun = 'localContent'></content-box>
		<ul class="list-group">
			<li class="list-group-item" v-for = "item in list" :key = 'item.id'>
				<span class="badge">评论人:{{ item.name }}</span>
				{{ item.content }}
			</li>
		</ul>
	</div>
	<template id="box">
		<div>
			<div class="form-group">
				评论人:<input type="text" class="form-control" v-model = 'name'>
			</div>
			<div class="form-group">
				评论内容: <textarea class="form-control" v-model = 'content'></textarea>
			</div>
			<div class="form-group">
				评论人:<input type="button" class="btn btn-promary" value="发表评论" @click = 'postContent'>
			</div>
		</div>
	</template>
	<script type="text/javascript" src="lib/vue-2.4.0.js"></script>
	<script type="text/javascript">
		let contentBox = {
			template:'#box',
			data(){
				return {
					name:'',
					content:''
				}
			},
			methods:{
				postContent(){
					//1.将评论数据存到localstorage
					//2.由父组件渲染
					//①获取当前评论对象
					// console.log('aa')
					if(!this.name.trim().length || !this.content.trim().length ) return false
					let list = {id:Date.now(),name:this.name,content:this.content};
					//②从localstorage获取所有的评论数据 -->预设key值
					let history = JSON.parse(localStorage.getItem('historyList') || '[]');
					//③添加到数组对象中
					history.unshift(list);
					//④存储最新的评论
					localStorage.setItem('historyList', JSON.stringify(history));
					//最后通过自定义事件刷新列表
					this.$emit('fun')
					this.content = this.name = '';
				}
			}

		}
		let vm = new Vue({
			el:'#app',
			data:{
				list:[
					{id:Date.now(),name:'小明',content:'放学别走!'},
					{id:Date.now(),name:'小新',content:'打台球去!'},
					{id:Date.now(),name:'小北',content:'放学一起走!'},
					{id:Date.now(),name:'小黑',content:'放学轰趴去!'},
				]
			},
			methods:{
				//渲染数据
				localContent(){
					//1.从localstorage获取所有的评论数据 -->预设key值
					let history = JSON.parse(localStorage.getItem('historyList') || '[]');
					console.log(history)
					this.list= history;
				}
			},
			created(){
				this.localContent();
			},
			components:{
				//组件名:组件模板对象
				contentBox
			}
		})
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42595284/article/details/83107806