1. 程式人生 > >vue 評論列表案例

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>